<?php

// 订单控制器

namespace app\api\controller;

use app\api\controller\Base;
use app\api\model\PaymentOrder;
use app\api\model\PaymentOrderRefund;
use app\api\model\PaymentOtherOrder;
use app\api\model\PaymentOrderPaid;
use app\api\model\PaymentOrderAlipayPaid;
use app\api\model\PaymentCash;
use app\api\model\PaymentIpGraylist;
use app\api\model\PaymentIpBlacklist;
use app\api\model\PaymentUserWhitelist;
use app\api\model\PaymentUserBlacklist;
use app\api\model\PaymentMobileBlacklist;
use app\api\model\PaymentIdCardBlacklist;
use app\api\model\PaymentCardWhitelist;
use app\api\model\PaymentCardBlacklist;
use think\facade\Cache;
use think\facade\Env;
use think\facade\Log;
use think\facade\Request;
use think\facade\Response;

class Order extends Base
{

    // Redis缓存驱动
    public $redis;

    public function initialize()
    {
        parent::initialize();
        // redis连接缓存驱动
        $this->redis = Cache::store('redis');
        // 文件连接缓存驱动
        // $this->redis =Cache::store('file');
    }

    /**
     * 创建支付订单
     */
    public function create()
    {
        try {
            // 表单数据
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Order');
            if (true !== $result) {
                return ['code' => 11000, 'msg' => $result];
            }

            // 此商户号全部配置
            $merchant = $this->redis->get($data['merchant_id']);
            if (!$merchant || $merchant['status'] != 1) {
                return ['code' => 11001, 'msg' => '商户号不存在或者被禁用'];
            }

            // 商户号配置值
            $merchant_value = $merchant['value'];
            $key = $merchant_value['key'];
            // 签名验证
            $sign = md5('merchant_id=' . $data['merchant_id'] . '&merchant_order_id=' . $data['merchant_order_id'] . '&cash=' . $data['cash'] . '&type=' . $data['type'] . '&return_url=' . $data['return_url'] . '&notify_url=' . $data['notify_url'] . '&ip=' . $data['ip'] . '&start_time=' . $data['start_time'] . '&random_string=' . $data['random_string'] . '&key=' . $key);
            if ($sign != $data['sign']) {
                return ['code' => 11002, 'msg' => '签名错误'];
            }

            // 支付开关
            $payment_open = $this->redis->get('payment_open');
            if (!$payment_open || $payment_open['status'] != 1) {
                return ['code' => 11003, 'msg' => '支付关闭'];
            }

            // 访问请求ip地址
            $request_ip = Request::instance()->ip();
            if ($merchant_value['pay_ip']) {
                if (!in_array($request_ip, $merchant_value['pay_ip'])) {
                    return ['code' => 11004, 'msg' => '请求服务器IP不在白名单中'];
                }
            }

            // 商户号是否设置开始和结束时间
            if ($merchant_value['start_time'] != $merchant_value['end_time']) {
                $now_second = time() - strtotime(date('Y-m-d'));
                if ($merchant_value['start_time'] > $now_second || $merchant_value['end_time'] < $now_second) {
                    return ['code' => 11005, 'msg' => "系统设置商户一天交易时间只能在{$merchant_value['start_time']}秒和{$merchant_value['end_time']}秒之间"];
                }
            }

            // 接收的应用ID是否存在
            if ($data['app_id'] != 0) {
                if (!in_array($data['app_id'], $merchant_value['app_id'])) {
                    return ['code' => 11006, 'msg' => '应用ID不存在'];
                }
            }

            // 交易类型（充值）
            $trade_type = $this->redis->get('consumption');
            if (!$trade_type || $trade_type['status'] != 1) {
                return ['code' => 11007, 'msg' => '交易类型已经关闭'];
            }

            // 商户号没有开通此交易类型
            if ($data['trade_type'] != 'consumption' || !in_array($data['trade_type'], $merchant_value['trade_type'])) {
                return ['code' => 11008, 'msg' => '商户号交易类型不存在'];
            }

            $bank_ip_blacklist = PaymentIpBlacklist::where('id', $data['ip'])->find();
            if ($bank_ip_blacklist) {
                return ['code' => 11009, 'msg' => '此用户IP已进黑名单'];
            }

            $old_type = $data['type'];    // 原始支付类型            
            $user_blacklist_status = 1;
            if ($data['id_card'] != 0) {
                // 用户身份证是否在黑名单中
                $user_blacklist_info = PaymentIdCardBlacklist::where('merchant_id', $data['merchant_id'])
                    ->where('id_card', $data['id_card'])
                    ->where('app_id', $data['app_id'])
                    ->find();
                if ($user_blacklist_info && $user_blacklist_info['status'] == 1) {

                    if (empty($user_blacklist_info['payment_type'])) {
                        return ['code' => 11010, 'msg' => '此用户身份证已进黑名单'];
                    }
                    if ($user_blacklist_info['mode'] == '0') {
                        return ['code' => 11010, 'msg' => '此用户身份证已进黑名单'];
                    }
                    if ($user_blacklist_info['mode'] == '1') {
                        if ($old_type == 'wechat_app') {
                            $data['type'] = 'alipay_app';
                        }
                        if ($old_type == 'wechat_h5') {
                            $data['type'] = 'alipay_h5';
                        }

                        $user_blacklist_info_type_company_config = json_decode($user_blacklist_info['type_company_config'], true);
                        if (is_array($user_blacklist_info_type_company_config)) {
                            if ($user_blacklist_info['pay_polling_open'] == '1') {
                                shuffle($user_blacklist_info_type_company_config);
                            }
                            $user_blacklist_company = $user_blacklist_info_type_company_config;
                        }

                        $merchant_value['vip_user_open'] = 0;
                        $user_blacklist_status = 0;
                    }
                }
            }

            if ($user_blacklist_status) {
                if ($data['mobile'] != 0) {
                    // 用户手机号是否在黑名单中
                    $user_blacklist_info = PaymentMobileBlacklist::where('merchant_id', $data['merchant_id'])
                        ->where('mobile', $data['mobile'])
                        ->where('app_id', $data['app_id'])
                        ->find();
                    if ($user_blacklist_info && $user_blacklist_info['status'] == 1) {

                        if (empty($user_blacklist_info['payment_type'])) {
                            return ['code' => 11011, 'msg' => '此用户手机号已进黑名单'];
                        }
                        if ($user_blacklist_info['mode'] == '0') {
                            return ['code' => 11011, 'msg' => '此用户手机号已进黑名单'];
                        }
                        if ($user_blacklist_info['mode'] == '1') {
                            if ($old_type == 'wechat_app') {
                                $data['type'] = 'alipay_app';
                            }
                            if ($old_type == 'wechat_h5') {
                                $data['type'] = 'alipay_h5';
                            }

                            $user_blacklist_info_type_company_config = json_decode($user_blacklist_info['type_company_config'], true);
                            if (is_array($user_blacklist_info_type_company_config)) {
                                if ($user_blacklist_info['pay_polling_open'] == '1') {
                                    shuffle($user_blacklist_info_type_company_config);
                                }
                                $user_blacklist_company = $user_blacklist_info_type_company_config;
                            }

                            $merchant_value['vip_user_open'] = 0;
                            $user_blacklist_status = 0;
                        }
                    }
                }
            }

            if ($user_blacklist_status) {
                if ($data['user_id'] != 0) {
                    // 用户是否在黑名单中
                    $user_blacklist_info = PaymentUserBlacklist::where('merchant_id', $data['merchant_id'])
                        ->where('user_id', $data['user_id'])
                        ->where('app_id', $data['app_id'])
                        ->find();
                    if ($user_blacklist_info && $user_blacklist_info['status'] == 1) {

                        if (empty($user_blacklist_info['payment_type'])) {
                            return ['code' => 11012, 'msg' => '此用户ID已进黑名单'];
                        }
                        if ($user_blacklist_info['mode'] == '0') {
                            return ['code' => 11012, 'msg' => '此用户ID已进黑名单'];
                        }
                        if ($user_blacklist_info['mode'] == '1') {
                            if ($old_type == 'wechat_app') {
                                $data['type'] = 'alipay_app';
                            }
                            if ($old_type == 'wechat_h5') {
                                $data['type'] = 'alipay_h5';
                            }

                            $user_blacklist_info_type_company_config = json_decode($user_blacklist_info['type_company_config'], true);
                            if (is_array($user_blacklist_info_type_company_config)) {
                                if ($user_blacklist_info['pay_polling_open'] == '1') {
                                    shuffle($user_blacklist_info_type_company_config);
                                }
                                $user_blacklist_company = $user_blacklist_info_type_company_config;
                            }

                            $merchant_value['vip_user_open'] = 0;
                            $user_blacklist_status = 0;
                        }
                    }
                }
            }

            // 支付类型
            $payment_type = $this->redis->get($data['type']);
            if (!$payment_type || $payment_type['status'] != 1) {
                return ['code' => 11013, 'msg' => "支付类型{$payment_type['title']}已经关闭"];
            }

            // 商户号没有开通此支付类型
            if (!in_array($data['type'], $merchant_value['payment_type'])) {
                return ['code' => 11014, 'msg' => "商户号没有开通{$payment_type['title']}"];
            }

            $min_recharge_cash = $merchant_value['min_recharge_cash'][$data['type']];
            $max_recharge_cash = $merchant_value['max_recharge_cash'][$data['type']];
            // 充值金额在不在商户号配置的范围中
            if ($min_recharge_cash > $data['cash'] || $max_recharge_cash < $data['cash']) {
                return ['code' => 11015, 'msg' => "{$payment_type['title']},商户号充值金额只能在{$min_recharge_cash}和{$max_recharge_cash}之间"];
            }

            // 此商户号今天充值的金额总数
            $merchant_day_recharge_cash_sum = $merchant_value['day_recharge_cash_sum'];
            $merchant_day_recharge_cash = $this->redis->get($data['merchant_id'] . '_day_recharge_cash_sum');
            if ($merchant_day_recharge_cash && $merchant_day_recharge_cash > $merchant_day_recharge_cash_sum * 100) {
                //payment_log(100000, $data, "此商户号（{$data['merchant_id']}）今天充值的金额总数超过了商户号每天设置充值的金额总数", false);
                Log::record("{$data['merchant_id']}今天充值的金额超过今天设置的总数{$merchant_day_recharge_cash_sum}", 'notice');
                return ['code' => 11016, 'msg' => "商户号今天充值的金额，已经到达系统设置的商户号每天最多充值的金额总数({$merchant_day_recharge_cash_sum})"];
            }

            // 此商户号今天充值的支付类型金额总数
            $merchant_day_recharge_type_cash_sum = $merchant_value['day_recharge_type_cash_sum'][$data['type']];
            $merchant_day_recharge_type_cash = $this->redis->get($data['merchant_id'] . '_day_recharge_type_cash_sum_' . $data['type']);
            if ($merchant_day_recharge_type_cash && $merchant_day_recharge_type_cash > $merchant_day_recharge_type_cash_sum * 100) {
                //payment_log(100000, $data, "此商户号（{$data['merchant_id']}）今天充值的支付类型金额总数超过了商户号每天设置充值的支付类型金额总数", false);
                Log::record("{$data['merchant_id']}今天充值的支付类型金额超过今天设置的总数{$merchant_day_recharge_type_cash_sum}", 'notice');
                return ['code' => 11017, 'msg' => "商户号今天充值的支付类型金额，已经到达系统设置的商户号每天最多充值的支付类型金额总数({$merchant_day_recharge_type_cash_sum})"];
            }

            $vip = isset($data['vip']) ? $data['vip'] : 0;

            // 是不是开启vip充值
            if ($vip == 1 && $merchant_value['vip_open'] == 1) {
                $type_company_config = 'vip_type_company_config';
            } else {
                $type_company_config = 'type_company_config';
            }

            // 是不是根据支付类型存在支付公司
            if (!isset($merchant_value[$type_company_config][$data['type']])) {
                return ['code' => 11018, 'msg' => '商户号未配置支付公司'];
            }

            $order_id = date('ymdHis') . random(8);    // 平台订单号
            $now_time = time();

            // 商户发送参数
            $merchant_order_create_param = [
                'version' => $data['version'], // 版本号
                'merchant_id' => $data['merchant_id'], // 商户号
                'merchant_order_id' => $data['merchant_order_id'], // 商户订单号
                'app_id' => $data['app_id'], // 应用id
                'cash' => $data['cash'], // 充值金额（元）
                'type' => $data['type'], // 支付类型，支付宝或微信等等
                'trade_type' => $data['trade_type'], // 交易类型：比如充值、代付
                'body' => $data['body'], // 商品名称
                'name' => $data['name'], // 姓名
                'id_card' => $data['id_card'], // 身份证号
                'mobile' => $data['mobile'], // 手机号
                'return_url' => $data['return_url'], // 支付完成调转地址
                'notify_url' => $data['notify_url'], // 支付成功服务端通知地址
                'ip' => $data['ip'], // 客户端ip
                'user_id' => $data['user_id'], // 用户id
                'channel_id' => $data['channel_id'], // 渠道id
                'system' => isset($data['system']) ? $data['system'] : '', // 系统
                'shop_id' => isset($data['cid']) ? $data['cid'] : '', // 商品id
                'vip' => $vip, // vip充值
                'business_type' => isset($data['business_type']) ? $data['business_type'] : '', // 业务类型
                'bank_code' => isset($data['bank_code']) ? $data['bank_code'] : '', // 银行编号
                'wxappid' => isset($data['wxappid']) ? $data['wxappid'] : '', // 微信appid
                'wxopenid' => isset($data['wxopenid']) ? $data['wxopenid'] : '', // 微信wxopenid
                'format' => $data['format'], // 返回格式
                'sign_type' => $data['sign_type'], // 签名类型
                'extra' => isset($data['extra']) ? $data['extra'] : '', // 商户自定义备注
                'start_time' => $data['start_time'], // 创建时间（时间戳）
                'random_string' => $data['random_string'], // 随机字符串
                'sign' => $data['sign'], // 签名
                'key' => $key, // 密钥
                'request_ip' => $request_ip, // 访问请求ip地址
            ];

            // 平台订单表数据
            $local_order_param = [
                'order_id' => $order_id, // 平台订单号
                'merchant_id' => $data['merchant_id'], // 商户号
                'merchant_order_id' => $data['merchant_order_id'], // 商户订单号
                'app_id' => $data['app_id'], // 应用id
                'cash' => intval(strval($data['cash'] * 100)), // 充值金额
                'now_cash' => 0, // 实际金额
                'type' => $data['type'], // 支付类型，支付宝或微信等等
                'trade_type' => $data['trade_type'], // 交易类型：比如充值、代付
                'user_id' => $data['user_id'], // 用户id
                'shop_id' => isset($data['cid']) ? $data['cid'] : '', // 商品id
                'channel_id' => isset($data['channel_id']) ? $data['channel_id'] : '', // 渠道
                'system' => isset($data['system']) ? $data['system'] : '', // 系统
                'create_time' => $now_time, // 订单创建时间
                'update_time' => $now_time, // 订单更新时间
                'company' => strstr($merchant_value[$type_company_config][$data['type']][0], '_', true), // 支付公司名称
                'child_company' => $merchant_value[$type_company_config][$data['type']][0], // 支付公司子商户号名称
                'status' => 1, // 状态
                'other_order_id' => '', // 第三方订单号
                'create_param' => json_encode($merchant_order_create_param, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), // 创建商户号发送参数数据
            ];
            // 捕获异常,可能平台订单表数据写入失败
            try {
                PaymentOrder::create($local_order_param);
            } catch (\Exception $e) {
                payment_log(100002, $local_order_param, $e->getMessage());
                return ['code' => 11019, 'msg' => '商户订单号重复'];
            }

            $root = '/api.php/order/returl';
            $tj_return_url = Request::instance()->domain() . $root . '/order_id/' . $order_id;

            // 发送给第三方支付公司参数
            $param['merchant_id'] = $data['merchant_id'];                               // 商户号
            $param['order_id'] = $order_id;                                             // 平台订单号
            $param['type'] = $data['type'];                                             // 支付类型
            $param['cash'] = $data['cash'];                                             // 金额
            $param['body'] = $data['body'];                                             // 商品名称
            $param['name'] = $data['name'];                                             // 姓名
            $param['id_card'] = $data['id_card'];                                       // 身份证号
            $param['mobile'] = $data['mobile'];                                         // 手机号
            $param['ip'] = $data['ip'];                                                 // 客户端ip
            $param['user_id'] = $data['user_id'];                                       // 用户id
            $param['channel_id'] = $data['channel_id'];                                 // 渠道id
            $param['return_url'] = $data['return_url'];                                 // 支付完成跳转界面
            $param['tj_return_url'] = $tj_return_url;                                   // 封装支付完成跳转界面
            $param['now_time'] = $now_time;                                             // 现在时间
            $param['vip_user'] = 0;                                                     // vip用户
            // 网银参数
            $param['business_type'] = $merchant_order_create_param['business_type'];    // 业务类型
            $param['bank_code'] = $merchant_order_create_param['bank_code'];            // 银行编号
            // 微信参数
            $param['wxappid'] = $merchant_order_create_param['wxappid'];                // 微信appid
            $param['wxopenid'] =  $merchant_order_create_param['wxopenid'];             // 微信wxopenid

            // 商品名称是平台订单号
            $body_order = $this->redis->get('body_order');
            if ($body_order && $body_order['status'] == 1) {
                $param['body'] = '订单号' . $order_id;        // 商品名称是平台订单号
            }

            // 实例化第三方订单模型
            $other_order_obj = new PaymentOtherOrder();

            // 提供支付类型的子支付公司中的商户号配置
            $all_company = $merchant_value[$type_company_config][$data['type']];

            // 商户号是否开启支付公司轮循（随机轮循）
            if ($merchant_value['pay_polling_open'][$data['type']] == 1) {
                // 支付公司轮循开关
                $pay_polling_open = $this->redis->get('pay_polling_open');
                if ($pay_polling_open && $pay_polling_open['status'] == 1) {
                    shuffle($all_company);
                }
            }

            // 商户号是否开启支付公司轮循（顺序轮循）
            if ($merchant_value['pay_polling_open'][$data['type']] == 2) {
                // 支付公司轮循开关
                $pay_polling_open = $this->redis->get('pay_polling_open');
                if ($pay_polling_open && $pay_polling_open['status'] == 1) {
                    $merchant_id_pay_company = $data['merchant_id'] . '_pay_company';
                    $now_merchant_id_pay_company = $this->redis->get($merchant_id_pay_company);
                    if ($now_merchant_id_pay_company) {
                        $all_company = array_merge(array_diff($all_company, $now_merchant_id_pay_company), $now_merchant_id_pay_company);
                    }
                }
            }

            // 商户号是否开启vip用户
            if ($merchant_value['vip_user_open'] == 1 && $data['user_id'] != 0) {
                // 优质支付通道
                $all_good_company = $this->redis->get('all_good_company');
                if ($all_good_company && $all_good_company['status'] == 1) {
                    // 用户是否在白名单中
                    $user_whitelist = PaymentUserWhitelist::where('merchant_id', $data['merchant_id'])
                        ->where('user_id', $data['user_id'])
                        ->where('app_id', $data['app_id'])
                        ->find();
                    if ($user_whitelist && $user_whitelist['status'] == 1) {
                        $all_good_company_value_keys = [];
                        $all_good_company_value = $all_good_company['value'];
                        if (!empty($all_good_company_value)) {
                            foreach ($all_good_company_value as $all_good_company_value_key => $all_good_company_value_value) {
                                if (is_array($all_good_company_value[$all_good_company_value_key]['payment_type'])) {
                                    if (in_array($data['type'], $all_good_company_value[$all_good_company_value_key]['payment_type'])) {
                                        $all_good_company_value_keys[] = $all_good_company_value_key;
                                    }
                                }
                            }
                            // 优质支付公司轮循开关（打乱数组）
                            $good_company_polling_open = $this->redis->get('good_company_polling_open');
                            if ($good_company_polling_open && $good_company_polling_open['status'] == 1) {
                                shuffle($all_good_company_value_keys);
                            }
                            $all_company_merge = array_merge($all_good_company_value_keys, $all_company);
                            $all_company = array_unique($all_company_merge);
                            $param['vip_user'] = 1;    // vip用户
                        }
                    }
                }
            }


            // 黑名单用户对应公司
            if (isset($user_blacklist_company)) {
                $all_company = $user_blacklist_company;
            }


            // $all_company所有子公司的集合（数组）
            foreach ($all_company as $children_company) {

                // 总支付公司名称
                $payment_company = strstr($children_company, '_', true);
                // 总支付公司名称配置
                $payment_company_config = $this->redis->get($payment_company);
                // 总支付公司配置状态
                if (!$payment_company_config || $payment_company_config['status'] != 1) {
                    continue;
                }

                // 判断支付公司中的子商户号配置状态是否开启、是否提供支付类型
                $children_company_config = $this->redis->get($children_company);
                if (!$children_company_config || $children_company_config['status'] != 1 || !in_array($data['type'], $children_company_config['value']['payment_type'])) {
                    continue;
                }

                // 绑定白名单商户号不受限制
                if (is_array($children_company_config['value']['bind_merchant']) && in_array($data['merchant_id'], $children_company_config['value']['bind_merchant'])) {
                    // 白名单商户号
                } else {

                    // 支付公司是否设置开始和结束时间
                    if ($children_company_config['value']['start_time'] != $children_company_config['value']['end_time']) {
                        $now_second = time() - strtotime(date('Y-m-d'));
                        if ($children_company_config['value']['start_time'] > $now_second || $children_company_config['value']['end_time'] < $now_second) {
                            continue;
                        }
                    }

                    $children_company_min_recharge_cash = $children_company_config['value']['min_recharge_cash'][$data['type']];
                    $children_company_max_recharge_cash = $children_company_config['value']['max_recharge_cash'][$data['type']];
                    // 充值金额在不在支付公司的充值范围中
                    if ($children_company_min_recharge_cash > $data['cash'] || $children_company_max_recharge_cash < $data['cash']) {
                        continue;
                    }

                    // 支付类型对应的固定充值金额
                    $children_company_config_payment_type_cash = $children_company_config['value']['payment_type_cash'][$data['type']];
                    if ($children_company_config_payment_type_cash) {
                        if (!in_array(floatval($data['cash']), $children_company_config_payment_type_cash)) {
                            continue;
                        }
                    }

                    // 创建订单间隔多少秒
                    $children_company_config_second_ok = $children_company_config['value']['second_ok'];
                    if ($children_company_config_second_ok != '0') {
                        $children_company_second_ok = $children_company . '_second_ok';
                        $now_children_company_second_ok = $this->redis->has($children_company_second_ok);
                        if ($now_children_company_second_ok) {
                            continue;
                        } else {
                            // 设置支付子公司间隔多少秒
                            $this->redis->set($children_company_second_ok, 1, $children_company_config_second_ok);
                        }
                    }

                    // 此支付公司中的子商户号今天已经充值的金额总数
                    $children_day_recharge_cash_sum = $children_company_config['value']['day_recharge_cash_sum'];
                    $now_children_day_recharge_cash_sum = $this->redis->get($children_company . '_day_recharge_cash_sum');
                    if ($now_children_day_recharge_cash_sum && $now_children_day_recharge_cash_sum > $children_day_recharge_cash_sum * 100) {
                        // payment_log(100004, $children_company, "此支付公司子商户号（{$children_company}）今天充值的金额总数超过了支付公司子商户号配置今天最多充值金额总数({$children_day_recharge_cash_sum})", false);
                        continue;
                    }

                    // 此支付公司中的子商户号今天已经充值的支付类型金额总数
                    $children_day_recharge_type_cash_sum = $children_company_config['value']['day_recharge_type_cash_sum'][$data['type']];
                    $now_children_day_recharge_type_cash_sum = $this->redis->get($children_company . '_day_recharge_type_cash_sum_' . $data['type']);
                    if ($now_children_day_recharge_type_cash_sum && $now_children_day_recharge_type_cash_sum > $children_day_recharge_type_cash_sum * 100) {
                        // payment_log(100004, $children_company, "此支付公司子商户号（{$children_company}）今天充值的支付类型金额总数超过了支付公司子商户号配置今天最多充值支付类型金额总数({$children_day_recharge_type_cash_sum})", false);
                        continue;
                    }

                    // 通道每天最多支付成功次数 
                    $children_company_config_success_count = $children_company_config['value']['success_count'];
                    if ($children_company_config_success_count != '0') {
                        $children_company_success_count = $children_company . '_success_count';
                        $now_children_company_success_count = $this->redis->get($children_company_success_count);
                        if ($now_children_company_success_count && $now_children_company_success_count >= $children_company_config_success_count) {
                            continue;
                        }
                    }

                    // vip用户
                    if ($param['vip_user'] == 1) {
                        // 优质通道是否绑定商户号
                        if (!empty($all_good_company['value'][$children_company]['bind_merchant'])) {
                            if (!in_array($data['merchant_id'], $all_good_company['value'][$children_company]['bind_merchant'])) {
                                continue;
                            }
                        }
                        // 子公司在优质支付通道中
                        if (in_array($children_company, $all_good_company_value_keys)) {
                            // 优质支付通道可能有个别用户风控
                            $children_company_user = $children_company . $data['user_id'];
                            $now_children_company_user = $this->redis->get($children_company_user);
                            if ($now_children_company_user) {
                                $this->redis->set($children_company_user, $now_children_company_user + 1, 100);
                            } else {
                                $this->redis->set($children_company_user, 1, 100);
                            }
                            // 优质支付通道一次不支付跳过
                            if ($now_children_company_user >= 5) {
                                continue;
                            }

                            // vip用户每天最多支付成功次数
                            $children_company_config_vip_user_success = $children_company_config['value']['vip_user_success'];
                            if ($children_company_config_vip_user_success != '0') {
                                // 优质支付通道对应的vip用户每天最多支付成功次数
                                $children_company_user_success = $children_company . $data['merchant_id'] . $data['user_id'];
                                $now_children_company_user_success = $this->redis->get($children_company_user_success);
                                if ($now_children_company_user_success && $now_children_company_user_success >= $children_company_config_vip_user_success) {
                                    continue;
                                }
                            }
                        }
                    }
                }

                // 合并支付公司默认商户号和子商户号配置
                $company_merge_values = array_merge($payment_company_config['value'], $children_company_config['value']);

                // 选择对应的支付公司                    
                $resarray = $other_order_obj->$payment_company($param, $company_merge_values);
                if ($resarray['code'] == 200) {
                    // 成功：跳出循环
                    break;
                }
            }


            // 商户号连续未支付订单报警开关
            $merchant_no_pay_warn_open = $this->redis->get('merchant_no_pay_warn_open');
            if ($merchant_no_pay_warn_open && $merchant_no_pay_warn_open['status'] == 1) {

                // 更新商户号支付类型对应未支付数量
                $now_merchant_no_pay_sum_warn_type = $data['merchant_id'] . '_no_pay_sum_warn_type_' . $data['type'];
                $now_merchant_no_pay_sum_warn = $this->redis->get($now_merchant_no_pay_sum_warn_type);
                if ($now_merchant_no_pay_sum_warn) {
                    $this->redis->inc($now_merchant_no_pay_sum_warn_type, 1);
                } else {
                    $expire = strtotime(date('Y-m-d', strtotime('+1 day'))) - time();
                    $this->redis->set($now_merchant_no_pay_sum_warn_type, 1, $expire);
                }

                // 报警间隔是否存在，存在跳过
                $merchant_no_pay_sum_warn_interval = $data['merchant_id'] . '_no_pay_sum_warn_interval';
                $merchant_no_pay_sum_warn_interval_exist = $this->redis->has($merchant_no_pay_sum_warn_interval);
                if (!$merchant_no_pay_sum_warn_interval_exist) {

                    // 商户号多少个连续未支付订单报警
                    $merchant_no_pay_sum_warn = $this->redis->get('merchant_no_pay_sum_warn');
                    if ($merchant_no_pay_sum_warn && $merchant_no_pay_sum_warn['value'] < $now_merchant_no_pay_sum_warn) {
                        // 报警
                        if ($data['merchant_id'] != 12345678) {
                            // 支付手机接收报警
                            $payment_mobile_warn = $this->redis->get('payment_mobile_warn');
                            if ($payment_mobile_warn && $payment_mobile_warn['status'] == 1) {
                                $payment_mobile_warn_value = $payment_mobile_warn['value'];
                                if (!empty($payment_mobile_warn_value)) {
                                    foreach ($payment_mobile_warn_value as $payment_mobile_warn_value_v) {
                                        // 阿里文本转语音外呼
                                        $Yuying = \Aliyun\Yuying\CallByTts::singleCallByTts($payment_mobile_warn_value_v, "商户名称：{$merchant_value['title']}：商户号：{$data['merchant_id']}：{$payment_type['title']}有{$now_merchant_no_pay_sum_warn}个未支付订单数量报警");
                                        if ($Yuying->Code != 'OK') {
                                            payment_error_log(600000, '阿里文本转语音外呼错误', json_encode($Yuying), false);
                                        }
                                    }
                                }
                            }
                        }
                        payment_log(100006, $data, "商户名称：{$merchant_value['title']}：商户号：{$data['merchant_id']}：{$payment_type['title']}有{$now_merchant_no_pay_sum_warn}个未支付订单数量报警", false);
                        // 设置报警间隔，默认60分钟
                        $this->redis->set($merchant_no_pay_sum_warn_interval, 1, 3600);
                    }
                }
            }


            // 商户号的支付类型对应的所有支付公司，全部关闭
            if (!isset($resarray)) {
                PaymentOrder::where(['order_id' => $order_id])->update(['company' => $payment_company, 'child_company' => $children_company, 'status' => 3]);
                //payment_log(100008, $data, "商户名称：{$merchant_value['title']}：商户号：{$data['merchant_id']}：{$payment_type['title']}：暂无可用支付", false);
                return ['code' => 11020, 'msg' => '商户暂无配置支付通道'];
            }
            // 订单状态：1:待支付 2:成功 3:失败 4:退款中 5:退款成功 6:退款失败 7:冻结 8:异常 9:驳回 10:关闭
            $status = $resarray['code'] == 200 ? 1 : 3;

            $update['status'] = $status;
            $update['company'] = $payment_company;
            $update['child_company'] = $children_company;
            $update['other_order_id'] = isset($resarray['other_order_id']) ? $resarray['other_order_id'] : '';
            $update['verify_param'] = isset($resarray['verify_param']) ? $resarray['verify_param'] : '';
            $update['return_param'] = isset($resarray['return_param']) ? substr($resarray['return_param'], 0, 60000) : '';
            $type =  isset($resarray['type']) ? $resarray['type'] : $data['type'];

            // 捕获异常,平台订单表数据更新失败
            try {
                PaymentOrder::where(['order_id' => $order_id])->update($update);
            } catch (\Exception $e) {
                payment_error_log(600002, $local_order_param, $e->getMessage());
                return ['code' => 11021, 'msg' => '订单更新失败'];
            }

            // 创建订单全部完成，成功
            if ($resarray['code'] == 200) {

                // 开启IP限制
                if ($merchant_value['ip_limit'] == 1) {
                    // IP灰名单
                    $gray_list_ip = 'gray_list_ip_' . $data['ip'];
                    $now_gray_list_ip = $this->redis->get($gray_list_ip);
                    if ($now_gray_list_ip) {
                        $this->redis->set($gray_list_ip, $now_gray_list_ip + 1, 60);
                    } else {
                        $this->redis->set($gray_list_ip, 1, 60);
                    }
                    if ($now_gray_list_ip > 3) {
                        PaymentIpGraylist::create(['id' => $data['ip'], 'remark' => $merchant_value['title'] . $data['user_id'], 'create_time' => time()]);
                    }

                    // 灰名单变黑名单ip个数
                    $gray_change_black_ip = $this->redis->get('gray_change_black_ip');
                    if ($gray_change_black_ip && $gray_change_black_ip['status'] == 1 && $gray_change_black_ip['value'] > 0) {
                        if ($now_gray_list_ip > $gray_change_black_ip['value']) {
                            PaymentIpBlacklist::create(['id' => $data['ip'], 'remark' => $merchant_value['title'] . '——接口来源', 'create_time' => time()]);
                        }
                    }
                }

                if (!in_array($data['type'], ['alipay_app', 'wechat_app', 'wechat_jsapi'])) {
                    // 封装网址跳转
                    if ($company_merge_values['jump_open'] == 1) {
                        $compan_url = base64_encode($resarray['url']);
                        $domain_name = $company_merge_values['domain_name'] ? $company_merge_values['domain_name'] : Request::instance()->domain();
                        $resarray['url'] = $domain_name . '/api.php/order/url?wz=' . $compan_url;
                    }
                }

                if ($data['format'] == 'jump') {
                    header("Location: {$resarray['url']}");
                    exit;
                }

                $output = ['code' => 10000, 'msg' => '成功', 'pay_url' => $resarray['url'], 'merchant_order_id' => $data['merchant_order_id'], 'order_id' => $param['order_id'], 'pay_url_type' => $type, 'sign' => $data['sign']];
                return Response::create($output, 'json')->options(['json_encode_param' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES]);
            } else {
                return ['code' => 11022, 'msg' => '暂无可用支付通道'];
            }
        } catch (\Exception $e) {
            payment_error_log(600004, input(), $e->getMessage(), false);
            return ['code' => 555, 'msg' => '系统异常'];
        }
    }

    /**
     * 查询订单
     */
    public function query()
    {
        try {
            // 表单数据
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Order.query');
            if (true !== $result) {
                return ['code' => 12000, 'msg' => $result];
            }

            // 此商户号全部配置
            $merchant = $this->redis->get($data['merchant_id']);
            if (!$merchant || $merchant['status'] != 1) {
                return ['code' => 12001, 'msg' => '商户号不存在或者被禁用'];
            }
            switch ($data['class']) {
                case '0':
                    $key = $merchant['value']['key'];
                    break;
                case '1':
                    $key = $merchant['value']['paid_key'];
                    break;
                case '2':
                    $key = $merchant['value']['paid_key'];
                    break;
                case '3':
                    $key = $merchant['value']['key'];
                    break;
                default:
                    return ['code' => 12002, 'msg' => '查询类型有误'];
            }

            // 签名验证
            $sign = md5('merchant_id=' . $data['merchant_id'] . '&merchant_order_id=' . $data['merchant_order_id'] . '&class=' . $data['class'] . '&start_time=' . $data['start_time'] . '&random_string=' . $data['random_string'] . '&key=' . $key);
            if ($sign != $data['sign']) {
                return ['code' => 12003, 'msg' => '签名错误'];
            }

            /*
              // 查询订单，不能在3秒内发送相同的签名，用redis处理。
              $order_query_key = 'order_query_' . $data['merchant_id'] . $data['sign'];
              $order_query = $this->redis->has($order_query_key);
              if ($order_query) {
              \think\Log::record('查询接口不能在3秒内发送相同的签名：' . json_encode($data), 'notice');
              return ['code' => 12004, 'msg' => '不能在3秒内发送相同的签名'];
              } else {
              // 设置3秒有效期
              $this->redis->set($order_query_key, 1, 3);
              }
             */

            // 查询条件
            $map['merchant_id'] = $data['merchant_id'];
            $map['merchant_order_id'] = $data['merchant_order_id'];

            switch ($data['class']) {
                case '0':
                    $info = PaymentOrder::where($map)->field('merchant_id,app_id,merchant_order_id,order_id,status,type,trade_type,cash,now_cash,create_time,update_time')->find();
                    if ($info) {
                        $info['cash'] = $info['cash'] / 100;
                        $info['now_cash'] = $info['now_cash'] / 100;
                    }
                    break;
                case '1':
                    $info = PaymentOrderPaid::where($map)->field('merchant_id,app_id,merchant_order_id,order_id,status,trade_type,cash,deduct_cash,mode,create_time,update_time')->find();
                    if ($info) {
                        $info['cash'] = $info['cash'] / 100;
                        $info['deduct_cash'] = $info['deduct_cash'] / 100;
                    }
                    break;
                case '2':
                    $info = PaymentOrderAlipayPaid::where($map)->field('merchant_id,app_id,merchant_order_id,order_id,status,trade_type,cash,deduct_cash,mode,create_time,update_time')->find();
                    if ($info) {
                        $info['cash'] = $info['cash'] / 100;
                        $info['deduct_cash'] = $info['deduct_cash'] / 100;
                    }
                    break;
                case '3':
                    $info = PaymentOrderRefund::where($map)->field('merchant_id,app_id,merchant_order_id,old_merchant_order_id,order_id,status,trade_type,cash,deduct_cash,old_cash,mode,create_time,update_time')->find();
                    if ($info) {
                        $info['cash'] = $info['cash'] / 100;
                        $info['deduct_cash'] = $info['deduct_cash'] / 100;
                        $info['old_cash'] = $info['old_cash'] / 100;
                    }
                    break;
                default:
                    return ['code' => 12005, 'msg' => '查询有误'];
            }

            if ($info) {
                $temp['code'] = 10000;
                $temp['msg'] = '查找成功';
                $find = $info->toArray();
                $output = array_merge($temp, $find);
                return Response::create($output, 'json')->options(['json_encode_param' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES]);
            } else {
                return ['code' => 12006, 'msg' => '订单不存在'];
            }
        } catch (\Exception $e) {
            payment_error_log(600006, input(), $e->getMessage(), false);
            return ['code' => 555, 'msg' => '系统异常'];
        }
    }

    /**
     * 创建银行卡代付订单
     */
    public function paid()
    {
        try {
            // 表单数据
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Paid');
            if (true !== $result) {
                return ['code' => 13000, 'msg' => $result, 'status' => 3];
            }

            // 此商户号全部配置
            $merchant = $this->redis->get($data['merchant_id']);
            if (!$merchant || $merchant['status'] != 1) {
                return ['code' => 13001, 'msg' => '商户号不存在或者被禁用', 'status' => 3];
            }

            // 商户号配置值
            $merchant_value = $merchant['value'];
            $key = $merchant_value['paid_key'];

            // 签名验证
            $sign = md5('merchant_id=' . $data['merchant_id'] . '&merchant_order_id=' . $data['merchant_order_id'] . '&cash=' . $data['cash'] . '&bank_card=' . $data['bank_card'] . '&start_time=' . $data['start_time'] . '&random_string=' . $data['random_string'] . '&key=' . $key);
            if ($sign != $data['sign']) {
                return ['code' => 13002, 'msg' => '签名错误', 'status' => 3];
            }

            // 支付开关
            $payment_open = $this->redis->get('payment_open');
            if (!$payment_open || $payment_open['status'] != 1) {
                return ['code' => 13003, 'msg' => '支付关闭', 'status' => 3];
            }

            // 访问请求ip地址
            $request_ip = Request::instance()->ip();
            if (!$merchant_value['paid_ip'] || !in_array($request_ip, $merchant_value['paid_ip'])) {
                return ['code' => 13004, 'msg' => '请求服务器IP不在白名单中', 'status' => 3];
            }

            // 接收的应用ID是否存在
            if ($data['app_id'] != 0) {
                if (!in_array($data['app_id'], $merchant_value['app_id'])) {
                    return ['code' => 13005, 'msg' => '应用ID不存在', 'status' => 3];
                }
            }

            // 银行卡代付开关
            $bank_card_paid_open = $this->redis->get('bank_card_paid_open');
            if (!$bank_card_paid_open || $bank_card_paid_open['status'] != 1) {
                return ['code' => 13006, 'msg' => '银行卡代付已经关闭', 'status' => 3];
            }

            $paid_start_time = $this->redis->get('paid_start_time');
            $paid_end_time = $this->redis->get('paid_end_time');
            // 每天代付开始和结束时间
            if ($paid_start_time['value'] != $paid_end_time['value']) {
                $now_second = time() - strtotime(date('Y-m-d'));
                if ($paid_start_time['value'] > $now_second || $paid_end_time['value'] < $now_second) {
                    return ['code' => 13007, 'msg' => "系统设置每天代付时间只能在{$paid_start_time['value']}秒和{$paid_end_time['value']}秒之间", 'status' => 3];
                }
            }

            // 交易类型不存在或者此商户号没有开通此交易类型
            if ($data['trade_type'] != 'paid' || !in_array($data['trade_type'], $merchant_value['trade_type'])) {
                return ['code' => 13008, 'msg' => '商户号交易类型不存在', 'status' => 3];
            }

            // 商户号是否开启api接口代付
            if ($merchant_value['api_paid'] != 1) {
                return ['code' => 13009, 'msg' => '商户号没有开启代付接口', 'status' => 3];
            }

            $bank_card_blacklist = PaymentCardBlacklist::get(['id' => $data['bank_card']]);
            if ($bank_card_blacklist) {
                return ['code' => 13010, 'msg' => '此银行卡已进黑名单', 'status' => 3];
            }

            // 代付接口请求相同帐号默认多少秒不能重复
            $paid_request_interval = $this->redis->get('paid_request_interval');
            $temp_bank_card = 'temp_' . $data['bank_card'];
            $temp_bank_card_exist = $this->redis->has($temp_bank_card);
            if ($temp_bank_card_exist) {
                return ['code' => 13011, 'msg' => "同一个银行卡{$paid_request_interval['value']}秒内重试无效", 'status' => 3];
            } else {
                $this->redis->set($temp_bank_card, 1, $paid_request_interval['value']);
            }

            // 商户号是否开启银行支付宝金额限制开关
            if ($merchant_value['paid_limit_open'] == 1) {
                // 全局代付银行支付宝金额限制开关
                $paid_cash_limit_open = $this->redis->get('paid_cash_limit_open');
                if ($paid_cash_limit_open && $paid_cash_limit_open['status'] == 1) {
                    // 银行卡或支付宝帐号白名单
                    $bank_card_whitelist = PaymentCardWhitelist::get(['id' => $data['bank_card']]);
                    if (!$bank_card_whitelist) {
                        $now_account_paid_cash = PaymentOrderPaid::where(['bank_card' => $data['bank_card']])->whereTime('create_time', 'today')->sum('cash');
                        if ($now_account_paid_cash >= $merchant_value['paid_cash_limit'] * 100) {
                            return ['code' => 13012, 'msg' => "此银行卡{$data['bank_card']}超过今天系统配置商户可代付额度", 'status' => 3];
                        }
                    }
                }
            }

            $paid_green_channel_open_status = false;         // 代付绿色通道关闭
            // 商户代付绿色通道是否开启
            if ($merchant_value['paid_green_channel_status'] == 1) {
                // 代付绿色通道总开关
                $paid_green_channel_open = $this->redis->get('paid_green_channel_open');
                if ($paid_green_channel_open && $paid_green_channel_open['status'] == 1) {
                    $paid_green_channel_open_status = true;  // 代付绿色通道开启
                }
            }

            // 此商户号银行卡今天已经代付的金额总数
            $merchant_day_paid_cash = $this->redis->get($data['merchant_id'] . '_day_paid_cash_sum');
            if ($merchant_day_paid_cash && $merchant_day_paid_cash > $merchant_value['day_paid_cash_sum'] * 100) {
                payment_log(100010, $data, "商户名称：{$merchant_value['title']}：商户号（{$data['merchant_id']}）今天银行卡代付的金额配置总数超过了商户号今天银行卡最多代付金额总数({$merchant_value['day_paid_cash_sum']})", false);
                return ['code' => 13013, 'msg' => "商户号银行卡今天的代付金额，已经到达系统设置的商户号银行卡每天最多代付金额总数({$merchant_value['day_paid_cash_sum']})", 'status' => 3];
            }

            // 代付金额在不在商户号配置的范围中
            if ($merchant_value['min_paid_cash'] > $data['cash'] || $merchant_value['max_paid_cash'] < $data['cash']) {
                return ['code' => 13014, 'msg' => "商户号代付金额只能在{$merchant_value['min_paid_cash']}和{$merchant_value['max_paid_cash']}之间", 'status' => 3];
            }

            if (empty($merchant_value['paid_company_config'])) {
                return ['code' => 13015, 'msg' => '商户号没有配置可用银行卡代付通道', 'status' => 3];
            }

            // 商户发送参数
            $merchant_order_create_param = [
                'version' => $data['version'], // 版本号
                'merchant_id' => $data['merchant_id'], // 商户号
                'merchant_order_id' => $data['merchant_order_id'], // 商户订单号
                'app_id' => $data['app_id'], // 应用id
                'cash' => $data['cash'], // 代付金额（元）
                'trade_type' => $data['trade_type'], // 交易类型：比如充值、代付
                'body' => $data['body'], // 付款说明
                'name' => $data['name'], // 姓名
                'id_card' => $data['id_card'], // 身份证
                'mobile' => $data['mobile'], // 手机号
                'account_type' => $data['account_type'], // 账户类型
                'bank_code' => $data['bank_code'], // 银行编号
                'bank_card' => $data['bank_card'], // 银行卡号
                'notify_open' => $data['notify_open'], // 通知开关
                'notify_url' => $data['notify_url'], // 通知地址
                'ip' => $data['ip'], // 客户端ip
                'user_id' => $data['user_id'], // 用户id
                'channel_id' => $data['channel_id'], // 渠道id
                'format' => $data['format'], // 返回格式
                'sign_type' => $data['sign_type'], // 签名类型
                'extra' => isset($data['extra']) ? $data['extra'] : '', // 商户自定义备注
                'start_time' => $data['start_time'], // 订单开始时间（时间戳）
                'random_string' => $data['random_string'], // 随机字符串
                'sign' => $data['sign'], // 签名
                'key' => $key, // 代付密钥
                'request_ip' => $request_ip, // 访问请求ip地址
            ];

            $cash = intval(strval($data['cash'] * 100));

            $paid_start_price = intval(strval($merchant_value['paid_start_price'] * 100));  // 每次代付开始扣除金额
            $paid_rate = $merchant_value['paid_rate'];                                      // 代付费率
            $paid_rate_cash = ceil($cash * $paid_rate);                                     // 费率金额
            $deduct_cash = $cash + $paid_start_price + $paid_rate_cash;                     // 扣除金额

            if (!$paid_green_channel_open_status) {
                $merchant_data = PaymentCash::get(['merchant_id' => $data['merchant_id']]);
                if ($deduct_cash > $merchant_data['paid_cash']) {
                    return ['code' => 13016, 'msg' => '商户代付余额不足', 'status' => 3];
                }
                $balance = $merchant_data['paid_cash'] - $deduct_cash;
            }

            $order_id = date('ymdHis') . random(8);                 // 平台订单号
            $now_time = time();                                     // 时间戳
            $data['bank_code'] = strtoupper($data['bank_code']);    // 银行编号

            $local_order_param = [
                'order_id' => $order_id, // 平台订单号
                'merchant_id' => $data['merchant_id'], // 商户号
                'merchant_order_id' => $data['merchant_order_id'], // 商户订单号
                'app_id' => $data['app_id'], // 应用id
                'cash' => $cash, // 代付金额
                'deduct_cash' => $deduct_cash, // 代付扣除金额
                'balance' => isset($balance) ? $balance : 0, // 代付余额
                'paid_green_channel_status' => $paid_green_channel_open_status ? 1 : 0, // 商户代付绿色通道是否开启
                'trade_type' => $data['trade_type'], // 交易类型：比如充值、代付
                'body' => $data['body'], // 付款说明
                'account_type' => $data['account_type'], // 账户类型：私户0，公户1
                'bank_code' => $data['bank_code'], // 银行编号
                'bank_card' => $data['bank_card'], // 收款方银行卡号
                'name' => $data['name'], // 姓名
                'user_id' => $data['user_id'], // 用户id
                'paid_start_price' => $paid_start_price, // 每次代付开始扣除金额
                'paid_rate' => $paid_rate, // 代付费率
                'create_param' => json_encode($merchant_order_create_param, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), // 创建商户发送参数数据
                'create_time' => $now_time, // 订单创建时间
                'update_time' => $now_time, // 订单更新时间
                'other_order_id' => 0, // 第三方订单号
                'mode' => 0, // 代付方式：0自动，1手动
                'status' => 1, // 状态：1:处理中 2:成功 3:失败 4:异常
            ];
            // 捕获异常,可能代付订单表数据写入失败
            try {
                PaymentOrderPaid::create($local_order_param);
            } catch (\Exception $e) {
                payment_log(100012, $local_order_param, $e->getMessage());
                return ['code' => 13017, 'msg' => '商户订单号重复', 'status' => 3];
            }

            if (!$paid_green_channel_open_status) {
                // 捕获异常,扣除商户代付余额
                try {
                    PaymentCash::where(['merchant_id' => $data['merchant_id']])
                        ->dec('paid_cash', $deduct_cash)
                        ->inc('paid_sum_cash', $deduct_cash)
                        ->inc('paid_count', 1)
                        ->update(['update_time' => time()]);
                } catch (\Exception $e) {
                    PaymentOrderPaid::where(['order_id' => $order_id])->update(['status' => 4, 'update_time' => time()]);
                    payment_error_log(600008, $local_order_param, $e->getMessage());
                    return ['code' => 13018, 'msg' => '商户余额错误', 'status' => 3];
                }
            }

            // 发送给第三方支付公司参数（代付）
            $param['merchant_id'] = $data['merchant_id'];          // 商户号
            $param['order_id'] = $order_id;                        // 平台订单号
            $param['cash'] = $data['cash'];                        // 金额
            $param['account_type'] = $data['account_type'];        // 账户类型
            $param['body'] = $data['body'];                        // 付款说明
            $param['name'] = $data['name'];                        // 姓名
            $param['id_card'] = $data['id_card'];                  // 身份证
            $param['mobile'] = $data['mobile'];                    // 手机号
            $param['bank_code'] = $data['bank_code'];              // 银行编号
            $param['bank_card'] = $data['bank_card'];              // 银行卡号
            $param['ip'] = $data['ip'];                            // 客户端ip
            $param['user_id'] = $data['user_id'];                  // 用户id
            $param['channel_id'] = $data['channel_id'];            // 渠道id
            $param['paid_class'] = 0;                              // 代付类型
            $param['now_time'] = $now_time;                        // 现在时间 
            // 实例化第三方代付订单模型
            $payment_order_paid_obj = new PaymentOrderPaid();

            $all_company = $merchant_value['paid_company_config'];

            // 银行卡代付轮循开关（打乱数组）
            $bank_paid_polling_open = $this->redis->get('bank_paid_polling_open');
            if ($bank_paid_polling_open && $bank_paid_polling_open['status'] == 1) {
                shuffle($all_company);
            }

            // 优质代付通道
            $all_good_paid_company = $this->redis->get('all_good_paid_company');
            if ($all_good_paid_company && $all_good_paid_company['status'] == 1) {

                $all_good_paid_company_value = $all_good_paid_company['value'];

                if (!empty($all_good_paid_company_value)) {
                    $all_good_paid_company_value_keys = [];
                    foreach ($all_good_paid_company_value as $all_good_paid_company_value_key => $all_good_paid_company_value_value) {

                        if (is_array($all_good_paid_company_value_value['bind_merchant'])) {

                            if ($all_good_paid_company_value_value['paid_class'] == 0 || $all_good_paid_company_value_value['paid_class'] == 2) {

                                if (in_array($data['merchant_id'], $all_good_paid_company_value_value['bind_merchant'])) {
                                    $all_good_paid_company_value_keys[] = $all_good_paid_company_value_key;
                                }
                            }
                        }
                    }

                    $good_paid_company_polling_open = $this->redis->get('good_paid_company_polling_open');
                    if ($good_paid_company_polling_open && $good_paid_company_polling_open['status'] == 1) {
                        shuffle($all_good_paid_company_value_keys);
                    }
                    $all_company_merge = array_merge($all_good_paid_company_value_keys, $all_company);
                    $all_company = array_unique($all_company_merge);
                }
            }

            // $all_company所有代付公司的集合（数组）
            foreach ($all_company as $children_company) {

                // 总代付公司名称
                $payment_company = strstr($children_company, '_', true);
                // 代付公司名称配置
                $children_company_config = $this->redis->get($children_company);
                // 判断总支付公司，状态是否开启、是否提供支付类型
                if (!$children_company_config || $children_company_config['status'] != 1) {
                    continue;
                }

                // 绑定白名单商户号不受限制
                if (is_array($children_company_config['value']['bind_merchant']) && in_array($data['merchant_id'], $children_company_config['value']['bind_merchant'])) {
                    // 白名单商户号
                } else {

                    // 此代付公司今天已经代付的金额总数
                    $children_day_paid_cash = $this->redis->get($children_company . '_day_paid_cash_sum');
                    $children_day_paid_cash_sum = $children_company_config['value']['day_paid_cash_sum'] * 100 - $data['cash'] * 100;
                    if ($children_day_paid_cash && $children_day_paid_cash > $children_day_paid_cash_sum) {
                        continue;
                    }

                    // 代付金额不能超过代付公司的天金额总数
                    if ($children_company_config['value']['day_paid_cash_sum'] < $data['cash']) {
                        continue;
                    }

                    // 代付公司是否设置开始和结束时间
                    if ($children_company_config['value']['start_time'] != $children_company_config['value']['end_time']) {
                        $now_second = time() - strtotime(date('Y-m-d'));
                        if ($children_company_config['value']['start_time'] > $now_second || $children_company_config['value']['end_time'] < $now_second) {
                            continue;
                        }
                    }

                    $children_company_min_paid_cash = $children_company_config['value']['min_paid_cash'];
                    $children_company_max_paid_cash = $children_company_config['value']['max_paid_cash'];
                    // 代付金额在不在代付公司的代付范围中
                    if ($children_company_min_paid_cash > $data['cash'] || $children_company_max_paid_cash < $data['cash']) {
                        continue;
                    }

                    // 创建代付间隔多少秒
                    $children_company_config_second_ok = $children_company_config['value']['second_ok'];
                    if ($children_company_config_second_ok != '0') {
                        $children_company_second_ok = $children_company . '_second_ok';
                        $now_children_company_second_ok = $this->redis->has($children_company_second_ok);
                        if ($now_children_company_second_ok) {
                            continue;
                        } else {
                            // 设置代付子公司间隔多少秒
                            $this->redis->set($children_company_second_ok, 1, $children_company_config_second_ok);
                        }
                    }

                    // 通道每天最多代付成功次数 
                    $children_company_config_success_count = $children_company_config['value']['success_count'];
                    if ($children_company_config_success_count != '0') {
                        $children_company_success_count = $children_company . '_success_count';
                        $now_children_company_success_count = $this->redis->get($children_company_success_count);
                        if ($now_children_company_success_count && $now_children_company_success_count >= $children_company_config_success_count) {
                            continue;
                        }
                    }

                    // 通道每天最多代付用户成功次数（银行卡）
                    $children_company_config_user_success_count = $children_company_config['value']['user_success_count'];
                    if ($children_company_config_user_success_count != '0') {
                        $children_company_user_success_count = $children_company . '_user_' . $data['bank_card'];
                        $now_children_company_user_success_count = $this->redis->get($children_company_user_success_count);
                        if ($now_children_company_user_success_count && $now_children_company_user_success_count >= $children_company_config_user_success_count) {
                            continue;
                        }
                    }

                    // 代付公司请求相同姓名默认多少秒不能重复
                    $children_company_config_name_interval = $children_company_config['value']['name_interval'];
                    if ($children_company_config_name_interval != '0') {
                        $children_company_name_interval = $children_company . '_name_' . $data['name'];
                        $now_children_company_name_interval = $this->redis->get($children_company_name_interval);
                        if ($now_children_company_name_interval) {
                            continue;
                        } else {
                            $this->redis->set($children_company_name_interval, 1, $children_company_config_name_interval);
                        }
                    }

                    // 禁止姓名
                    if (is_array($children_company_config['value']['deny_name']) && in_array($data['name'], $children_company_config['value']['deny_name'])) {
                        continue;
                    }
                }

                // 选择对应的代付公司                    
                $resarray = $payment_order_paid_obj->$payment_company($param, $children_company_config['value']);

                if (isset($resarray['code']) && $resarray['code'] == 400) {
                    // 没有请求到第三方，内部设置跳过
                    continue;
                }

                // 先设置只能请求一次（不确定因素多）
                break;
            }

            // 商户号的所有代付公司，全部关闭
            if (!isset($resarray)) {

                // 捕获异常,代付订单表数据改为失败
                try {
                    $company = strstr($children_company, 'Paid', true);
                    PaymentOrderPaid::where(['order_id' => $order_id])->update(['status' => 3, 'company' => $company, 'child_company' => $children_company, 'update_time' => time()]);
                } catch (\Exception $e) {
                    payment_error_log(600010, $local_order_param, $e->getMessage());
                }

                if (!$paid_green_channel_open_status) {
                    // 捕获异常,扣除商户代付余额(还原)
                    try {
                        PaymentCash::where(['merchant_id' => $data['merchant_id']])
                            ->inc('paid_cash', $deduct_cash)
                            ->dec('paid_sum_cash', $deduct_cash)
                            ->dec('paid_count', 1)
                            ->update(['update_time' => time()]);
                    } catch (\Exception $e) {
                        PaymentOrderPaid::where(['order_id' => $order_id])->update(['status' => 4, 'update_time' => time()]);
                        payment_error_log(600012, $local_order_param, $e->getMessage());
                    }
                }

                payment_log(100014, $data, "商户名称：{$merchant_value['title']}：商户号：{$data['merchant_id']}：暂无可用代付通道", false);
                return ['code' => 13019, 'msg' => '商户号暂无可用银行卡代付通道', 'status' => 3];
            }

            // 状态：1:处理中 2:成功 3:失败 4:异常 
            $update['status'] = $resarray['code'] == 300 ? 3 : 1;
            $update['company'] = strstr($children_company, 'Paid', true);
            $update['child_company'] = $children_company;
            $update['other_order_id'] = isset($resarray['other_order_id']) ? $resarray['other_order_id'] : '';
            $update['return_param'] = isset($resarray['return_param']) ? substr($resarray['return_param'], 0, 60000) : '';
            $update['update_time'] = time();

            $msg = isset($resarray['msg']) ? $resarray['msg'] : '未知错误';
            $msg = '提示：' . $msg;
            // 捕获异常,代付订单表数据改为失败
            try {
                PaymentOrderPaid::where(['order_id' => $order_id])->update($update);
            } catch (\Exception $e) {
                payment_error_log(600014, $local_order_param, $e->getMessage());
            }

            if ($update['status'] == 3) {
                if (!$paid_green_channel_open_status) {
                    // 捕获异常,扣除商户代付余额(还原)
                    try {
                        PaymentCash::where(['merchant_id' => $data['merchant_id']])
                            ->inc('paid_cash', $deduct_cash)
                            ->dec('paid_sum_cash', $deduct_cash)
                            ->dec('paid_count', 1)
                            ->update(['update_time' => time()]);
                    } catch (\Exception $e) {
                        PaymentOrderPaid::where(['order_id' => $order_id])->update(['status' => 4, 'update_time' => time()]);
                        payment_error_log(600016, $local_order_param, $e->getMessage());
                    }
                }
                return ['code' => 13020, 'msg' => $msg, 'status' => 3];
            }

            // 创建订单完成，成功
            $output = ['code' => 10000, 'msg' => $msg, 'status' => $update['status'], 'merchant_order_id' => $data['merchant_order_id'], 'order_id' => $order_id, 'sign' => $data['sign']];
            return Response::create($output, 'json')->options(['json_encode_param' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES]);
        } catch (\Exception $e) {
            payment_error_log(600018, input(), $e->getMessage(), false);
            return ['code' => 555, 'msg' => '系统异常', 'status' => 1];
        }
    }

    /**
     * 创建支付宝代付订单
     */
    public function alipayPaid()
    {
        try {
            // 表单数据
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'AlipayPaid');
            if (true !== $result) {
                return ['code' => 14000, 'msg' => $result, 'status' => 3];
            }

            // 此商户号全部配置
            $merchant = $this->redis->get($data['merchant_id']);
            if (!$merchant || $merchant['status'] != 1) {
                return ['code' => 14001, 'msg' => '商户号不存在或者被禁用', 'status' => 3];
            }

            // 商户号配置值
            $merchant_value = $merchant['value'];
            $key = $merchant_value['paid_key'];

            // 签名验证
            $sign = md5('merchant_id=' . $data['merchant_id'] . '&merchant_order_id=' . $data['merchant_order_id'] . '&cash=' . $data['cash'] . '&account=' . $data['account'] . '&start_time=' . $data['start_time'] . '&random_string=' . $data['random_string'] . '&key=' . $key);
            if ($sign != $data['sign']) {
                return ['code' => 14002, 'msg' => '签名错误', 'status' => 3];
            }

            // 支付开关
            $payment_open = $this->redis->get('payment_open');
            if (!$payment_open || $payment_open['status'] != 1) {
                return ['code' => 14003, 'msg' => '支付关闭', 'status' => 3];
            }

            // 访问请求ip地址
            $request_ip = Request::instance()->ip();
            if (!$merchant_value['paid_ip'] || !in_array($request_ip, $merchant_value['paid_ip'])) {
                return ['code' => 14004, 'msg' => '请求服务器IP不在白名单中', 'status' => 3];
            }

            // 接收的应用ID是否存在
            if ($data['app_id'] != 0) {
                if (!in_array($data['app_id'], $merchant_value['app_id'])) {
                    return ['code' => 14005, 'msg' => '应用ID不存在', 'status' => 3];
                }
            }

            // 支付宝代付开关
            $alipay_paid_open = $this->redis->get('alipay_paid_open');
            if (!$alipay_paid_open || $alipay_paid_open['status'] != 1) {
                return ['code' => 14006, 'msg' => '支付宝代付已经关闭', 'status' => 3];
            }

            $paid_start_time = $this->redis->get('paid_start_time');
            $paid_end_time = $this->redis->get('paid_end_time');
            // 每天代付开始和结束时间
            if ($paid_start_time['value'] != $paid_end_time['value']) {
                $now_second = time() - strtotime(date('Y-m-d'));
                if ($paid_start_time['value'] > $now_second || $paid_end_time['value'] < $now_second) {
                    return ['code' => 14007, 'msg' => "系统设置每天代付时间只能在{$paid_start_time['value']}秒和{$paid_end_time['value']}秒之间", 'status' => 3];
                }
            }

            // 交易类型不存在或者此商户号没有开通此交易类型
            if ($data['trade_type'] != 'paid' || !in_array($data['trade_type'], $merchant_value['trade_type'])) {
                return ['code' => 14008, 'msg' => '商户号交易类型不存在', 'status' => 3];
            }

            // 商户号是否开启api接口代付
            if ($merchant_value['api_paid'] != 1) {
                return ['code' => 14009, 'msg' => '商户号没有开启代付接口', 'status' => 3];
            }

            $bank_card_blacklist = PaymentCardBlacklist::get(['id' => $data['account']]);
            if ($bank_card_blacklist) {
                return ['code' => 14010, 'msg' => '此支付宝账号已进黑名单', 'status' => 3];
            }

            // 代付接口请求相同帐号默认多少秒不能重复
            $paid_request_interval = $this->redis->get('paid_request_interval');
            $temp_account = 'temp_' . $data['account'];
            $temp_account_exist = $this->redis->has($temp_account);
            if ($temp_account_exist) {
                return ['code' => 14011, 'msg' => "同一个支付宝帐号{$paid_request_interval['value']}秒内重试无效", 'status' => 3];
            } else {
                $this->redis->set($temp_account, 1, $paid_request_interval['value']);
            }

            // 商户是否开启银行支付宝金额限制开关
            if ($merchant_value['paid_limit_open'] == 1) {
                // 全局代付银行支付宝金额限制开关
                $paid_cash_limit_open = $this->redis->get('paid_cash_limit_open');
                if ($paid_cash_limit_open && $paid_cash_limit_open['status'] == 1) {
                    // 银行卡或支付宝帐号白名单
                    $bank_card_whitelist = PaymentCardWhitelist::get(['id' => $data['account']]);
                    if (!$bank_card_whitelist) {
                        $now_account_paid_cash = PaymentOrderAlipayPaid::where(['account' => $data['account']])->whereTime('create_time', 'today')->sum('cash');
                        if ($now_account_paid_cash >= $merchant_value['paid_cash_limit'] * 100) {
                            return ['code' => 14012, 'msg' => "此支付宝{$data['account']}超过今天系统配置商户可代付额度", 'status' => 3];
                        }
                    }
                }
            }

            $paid_green_channel_open_status = false;         // 代付绿色通道关闭
            // 商户号代付绿色通道是否开启
            if ($merchant_value['paid_green_channel_status'] == 1) {
                // 代付绿色通道总开关
                $paid_green_channel_open = $this->redis->get('paid_green_channel_open');
                if ($paid_green_channel_open && $paid_green_channel_open['status'] == 1) {
                    $paid_green_channel_open_status = true;  // 代付绿色通道开启
                }
            }

            // 此商户号支付宝今天已经代付的金额总数
            $merchant_day_alipay_paid_cash = $this->redis->get($data['merchant_id'] . '_day_alipay_paid_cash_sum');
            if ($merchant_day_alipay_paid_cash && $merchant_day_alipay_paid_cash > $merchant_value['day_alipay_paid_cash_sum'] * 100) {
                payment_log(100016, $data, "商户名称：{$merchant_value['title']}：商户号（{$data['merchant_id']}）今天支付宝代付的金额配置总数超过了商户号支付宝今天最多代付金额总数({$merchant_value['day_alipay_paid_cash_sum']})", false);
                return ['code' => 14013, 'msg' => "商户号今天的支付宝代付金额，已经到达系统设置的商户号支付宝每天最多代付金额总数({$merchant_value['day_alipay_paid_cash_sum']})", 'status' => 3];
            }

            // 代付金额在不在商户号配置的范围中
            if ($merchant_value['min_paid_cash'] > $data['cash'] || $merchant_value['max_paid_cash'] < $data['cash']) {
                return ['code' => 14014, 'msg' => "商户代付金额只能在{$merchant_value['min_paid_cash']}和{$merchant_value['max_paid_cash']}之间", 'status' => 3];
            }

            if (empty($merchant_value['alipay_paid_company_config'])) {
                return ['code' => 14015, 'msg' => '商户没有配置可用支付宝代付通道', 'status' => 3];
            }

            // 商户发送参数
            $merchant_order_create_param = [
                'version' => $data['version'], // 版本号
                'merchant_id' => $data['merchant_id'], // 商户号
                'merchant_order_id' => $data['merchant_order_id'], // 商户订单号
                'app_id' => $data['app_id'], // 应用id
                'cash' => $data['cash'], // 代付金额（元）
                'trade_type' => $data['trade_type'], // 交易类型：比如充值、代付
                'body' => $data['body'], // 付款说明
                'account' => $data['account'], // 支付宝帐号
                'name' => $data['name'], // 姓名
                'id_card' => $data['id_card'], // 身份证号
                'mobile' => $data['mobile'], // 手机号
                'notify_open' => $data['notify_open'], // 通知开关
                'notify_url' => $data['notify_url'], // 通知地址
                'ip' => $data['ip'], // 客户端ip
                'user_id' => $data['user_id'], // 用户id
                'channel_id' => $data['channel_id'], // 渠道id
                'format' => $data['format'], // 返回格式
                'sign_type' => $data['sign_type'], // 签名类型
                'extra' => isset($data['extra']) ? $data['extra'] : '', // 商户自定义备注
                'start_time' => $data['start_time'], // 订单开始时间（时间戳）
                'random_string' => $data['random_string'], // 随机字符串
                'sign' => $data['sign'], // 签名
                'key' => $key, // 代付密钥
                'request_ip' => $request_ip, // 访问请求ip地址
            ];

            $cash = intval(strval($data['cash'] * 100));

            $paid_start_price = intval(strval($merchant_value['alipay_paid_start_price'] * 100));  // 每次代付开始扣除金额
            $paid_rate = $merchant_value['alipay_paid_rate'];                                      // 代付费率
            $paid_rate_cash = intval(strval($cash * $paid_rate));                                  // 费率金额
            $deduct_cash = $cash + $paid_start_price + $paid_rate_cash;                            // 扣除金额

            if (!$paid_green_channel_open_status) {
                $merchant_data = PaymentCash::get(['merchant_id' => $data['merchant_id']]);
                if ($deduct_cash > $merchant_data['paid_cash']) {
                    return ['code' => 14016, 'msg' => '商户代付余额不足', 'status' => 3];
                }
                $balance = $merchant_data['paid_cash'] - $deduct_cash;
            }

            $order_id = date('ymdHis') . random(8);    // 平台订单号
            $now_time = time();

            $local_order_param = [
                'order_id' => $order_id, // 平台订单号
                'merchant_id' => $data['merchant_id'], // 商户号
                'merchant_order_id' => $data['merchant_order_id'], // 商户订单号
                'app_id' => $data['app_id'], // 应用id
                'cash' => $cash, // 代付金额
                'deduct_cash' => $deduct_cash, // 代付扣除金额
                'balance' => isset($balance) ? $balance : 0, // 代付余额
                'paid_green_channel_status' => $paid_green_channel_open_status ? 1 : 0, // 商户代付绿色通道是否开启
                'trade_type' => $data['trade_type'], // 交易类型：比如充值、代付
                'body' => $data['body'], // 付款说明
                'account' => $data['account'], // 支付宝帐号
                'name' => $data['name'], // 姓名
                'user_id' => $data['user_id'], // 用户id
                'paid_start_price' => $paid_start_price, // 每次代付开始扣除金额
                'paid_rate' => $paid_rate, // 代付费率
                'create_param' => json_encode($merchant_order_create_param, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), // 创建商户号发送参数数据
                'create_time' => $now_time, // 订单创建时间
                'update_time' => $now_time, // 订单更新时间
                'other_order_id' => 0, // 第三方订单号
                'mode' => 0, // 代付方式：0自动，1手动
                'status' => 1, // 状态：1:处理中 2:成功 3:失败 4:异常
            ];
            // 捕获异常,可能代付订单表数据写入失败
            try {
                PaymentOrderAlipayPaid::create($local_order_param);
            } catch (\Exception $e) {
                payment_log(100018, $local_order_param, $e->getMessage());
                return ['code' => 14017, 'msg' => '商户订单号重复', 'status' => 3];
            }

            if (!$paid_green_channel_open_status) {
                // 捕获异常,扣除商户代付余额
                try {
                    PaymentCash::where(['merchant_id' => $data['merchant_id']])
                        ->dec('paid_cash', $deduct_cash)
                        ->inc('paid_sum_cash', $deduct_cash)
                        ->inc('paid_count', 1)
                        ->update(['update_time' => time()]);
                } catch (\Exception $e) {
                    PaymentOrderAlipayPaid::where(['order_id' => $order_id])->update(['status' => 4, 'update_time' => time()]);
                    payment_error_log(600020, $local_order_param, $e->getMessage());
                    return ['code' => 14018, 'msg' => '商户余额错误', 'status' => 3];
                }
            }

            // 发送给第三方支付公司参数（代付）
            $param['merchant_id'] = $data['merchant_id'];          // 商户号
            $param['order_id'] = $order_id;                        // 平台订单号
            $param['cash'] = $data['cash'];                        // 金额 
            $param['body'] = $data['body'];                        // 付款说明
            $param['account'] = $data['account'];                  // 支付宝帐号
            $param['name'] = $data['name'];                        // 姓名
            $param['id_card'] = $data['id_card'];                  // 身份证
            $param['mobile'] = $data['mobile'];                    // 手机号
            $param['ip'] = $data['ip'];                            // 客户端ip
            $param['user_id'] = $data['user_id'];                  // 用户id
            $param['channel_id'] = $data['channel_id'];            // 渠道id
            $param['paid_class'] = 1;                              // 代付类型
            $param['now_time'] = $now_time;                        // 现在时间 
            // 实例化第三方代付订单模型
            $payment_order_paid_obj = new PaymentOrderAlipayPaid();

            $all_company = $merchant_value['alipay_paid_company_config'];

            // 支付宝代付轮循开关（打乱数组）
            $alipay_paid_polling_open = $this->redis->get('alipay_paid_polling_open');
            if ($alipay_paid_polling_open && $alipay_paid_polling_open['status'] == 1) {
                shuffle($all_company);
            }

            // 优质代付通道
            $all_good_paid_company = $this->redis->get('all_good_paid_company');
            if ($all_good_paid_company && $all_good_paid_company['status'] == 1) {

                $all_good_paid_company_value = $all_good_paid_company['value'];

                if (!empty($all_good_paid_company_value)) {
                    $all_good_paid_company_value_keys = [];
                    foreach ($all_good_paid_company_value as $all_good_paid_company_value_key => $all_good_paid_company_value_value) {

                        if (is_array($all_good_paid_company_value_value['bind_merchant'])) {

                            if ($all_good_paid_company_value_value['paid_class'] == 1 || $all_good_paid_company_value_value['paid_class'] == 2) {

                                if (in_array($data['merchant_id'], $all_good_paid_company_value_value['bind_merchant'])) {
                                    $all_good_paid_company_value_keys[] = $all_good_paid_company_value_key;
                                }
                            }
                        }
                    }

                    $good_paid_company_polling_open = $this->redis->get('good_paid_company_polling_open');
                    if ($good_paid_company_polling_open && $good_paid_company_polling_open['status'] == 1) {
                        shuffle($all_good_paid_company_value_keys);
                    }
                    $all_company_merge = array_merge($all_good_paid_company_value_keys, $all_company);
                    $all_company = array_unique($all_company_merge);
                }
            }

            // $all_company所有代付公司的集合（数组）
            foreach ($all_company as $children_company) {

                // 总代付公司名称
                $payment_company = strstr($children_company, '_', true);
                // 代付公司名称配置
                $children_company_config = $this->redis->get($children_company);
                // 判断总支付公司，状态是否开启、是否提供支付类型
                if (!$children_company_config || $children_company_config['status'] != 1) {
                    continue;
                }

                // 绑定白名单商户号不受限制
                if (is_array($children_company_config['value']['bind_merchant']) && in_array($data['merchant_id'], $children_company_config['value']['bind_merchant'])) {
                    // 白名单商户号
                } else {

                    // 此代付公司今天已经代付的金额总数
                    $children_day_paid_cash = $this->redis->get($children_company . '_day_paid_cash_sum');
                    $children_day_paid_cash_sum = $children_company_config['value']['day_paid_cash_sum'] * 100 - $data['cash'] * 100;
                    if ($children_day_paid_cash && $children_day_paid_cash > $children_day_paid_cash_sum) {
                        continue;
                    }

                    // 代付金额不能超过代付公司的天金额总数
                    if ($children_company_config['value']['day_paid_cash_sum'] < $data['cash']) {
                        continue;
                    }

                    // 代付公司是否设置开始和结束时间
                    if ($children_company_config['value']['start_time'] != $children_company_config['value']['end_time']) {
                        $now_second = time() - strtotime(date('Y-m-d'));
                        if ($children_company_config['value']['start_time'] > $now_second || $children_company_config['value']['end_time'] < $now_second) {
                            continue;
                        }
                    }

                    $children_company_min_paid_cash = $children_company_config['value']['min_paid_cash'];
                    $children_company_max_paid_cash = $children_company_config['value']['max_paid_cash'];
                    // 代付金额在不在代付公司的代付范围中
                    if ($children_company_min_paid_cash > $data['cash'] || $children_company_max_paid_cash < $data['cash']) {
                        continue;
                    }

                    // 创建代付间隔多少秒
                    $children_company_config_second_ok = $children_company_config['value']['second_ok'];
                    if ($children_company_config_second_ok != '0') {
                        $children_company_second_ok = $children_company . '_second_ok';
                        $now_children_company_second_ok = $this->redis->has($children_company_second_ok);
                        if ($now_children_company_second_ok) {
                            continue;
                        } else {
                            // 设置代付子公司间隔多少秒
                            $this->redis->set($children_company_second_ok, 1, $children_company_config_second_ok);
                        }
                    }

                    // 通道每天最多代付成功次数 
                    $children_company_config_success_count = $children_company_config['value']['success_count'];
                    if ($children_company_config_success_count != '0') {
                        $children_company_success_count = $children_company . '_success_count';
                        $now_children_company_success_count = $this->redis->get($children_company_success_count);
                        if ($now_children_company_success_count && $now_children_company_success_count >= $children_company_config_success_count) {
                            continue;
                        }
                    }

                    // 通道每天最多代付用户成功次数（支付宝帐号）
                    $children_company_config_user_success_count = $children_company_config['value']['user_success_count'];
                    if ($children_company_config_user_success_count != '0') {
                        $children_company_user_success_count = $children_company . '_user_' . $data['account'];
                        $now_children_company_user_success_count = $this->redis->get($children_company_user_success_count);
                        if ($now_children_company_user_success_count && $now_children_company_user_success_count >= $children_company_config_user_success_count) {
                            continue;
                        }
                    }

                    // 代付公司请求相同姓名默认多少秒不能重复
                    $children_company_config_name_interval = $children_company_config['value']['name_interval'];
                    if ($children_company_config_name_interval != '0') {
                        $children_company_name_interval = $children_company . '_name_' . $data['name'];
                        $now_children_company_name_interval = $this->redis->get($children_company_name_interval);
                        if ($now_children_company_name_interval) {
                            continue;
                        } else {
                            $this->redis->set($children_company_name_interval, 1, $children_company_config_name_interval);
                        }
                    }

                    // 禁止姓名
                    if (is_array($children_company_config['value']['deny_name']) && in_array($data['name'], $children_company_config['value']['deny_name'])) {
                        continue;
                    }
                }

                // 选择对应的代付公司                    
                $resarray = $payment_order_paid_obj->$payment_company($param, $children_company_config['value']);

                if (isset($resarray['code']) && $resarray['code'] == 400) {
                    // 没有请求到第三方，内部设置跳过
                    continue;
                }

                // 先设置只能请求一次（不确定因素多）
                break;
            }

            // 商户号的所有代付公司，全部关闭
            if (!isset($resarray)) {

                // 捕获异常,代付订单表数据改为失败
                try {
                    $company = strstr($children_company, 'Paid', true);
                    PaymentOrderAlipayPaid::where(['order_id' => $order_id])->update(['status' => 3, 'company' => $company, 'child_company' => $children_company, 'update_time' => time()]);
                } catch (\Exception $e) {
                    payment_error_log(600022, $local_order_param, $e->getMessage());
                }

                if (!$paid_green_channel_open_status) {
                    // 捕获异常,扣除商户代付余额(还原)
                    try {
                        PaymentCash::where(['merchant_id' => $data['merchant_id']])
                            ->inc('paid_cash', $deduct_cash)
                            ->dec('paid_sum_cash', $deduct_cash)
                            ->dec('paid_count', 1)
                            ->update(['update_time' => time()]);
                    } catch (\Exception $e) {
                        PaymentOrderAlipayPaid::where(['order_id' => $order_id])->update(['status' => 4, 'update_time' => time()]);
                        payment_error_log(600024, $local_order_param, $e->getMessage());
                    }
                }

                payment_log(100020, $data, "商户名称：{$merchant_value['title']}：商户号：{$data['merchant_id']}：暂无可用代付通道", false);
                return ['code' => 14019, 'msg' => '商户号暂无可用支付宝代付通道', 'status' => 3];
            }

            // 状态：1:处理中 2:成功 3:失败 4:异常 
            $update['status'] = $resarray['code'] == 300 ? 3 : 1;
            $update['company'] = strstr($children_company, 'Paid', true);
            $update['child_company'] = $children_company;
            $update['other_order_id'] = isset($resarray['other_order_id']) ? $resarray['other_order_id'] : '';
            $update['return_param'] = isset($resarray['return_param']) ? substr($resarray['return_param'], 0, 60000) : '';
            $update['update_time'] = time();

            $msg = isset($resarray['msg']) ? $resarray['msg'] : '未知错误';
            $msg = '提示：' . $msg;
            // 捕获异常,代付订单表数据改为失败
            try {
                PaymentOrderAlipayPaid::where(['order_id' => $order_id])->update($update);
            } catch (\Exception $e) {
                payment_error_log(600026, $local_order_param, $e->getMessage());
            }

            if ($update['status'] == 3) {
                if (!$paid_green_channel_open_status) {
                    // 捕获异常,扣除商户代付余额(还原)
                    try {
                        PaymentCash::where(['merchant_id' => $data['merchant_id']])
                            ->inc('paid_cash', $deduct_cash)
                            ->dec('paid_sum_cash', $deduct_cash)
                            ->dec('paid_count', 1)
                            ->update(['update_time' => time()]);
                    } catch (\Exception $e) {
                        PaymentOrderAlipayPaid::where(['order_id' => $order_id])->update(['status' => 4, 'update_time' => time()]);
                        payment_error_log(600028, $local_order_param, $e->getMessage());
                    }
                }
                return ['code' => 14020, 'msg' => $msg, 'status' => 3];
            }

            // 创建订单完成，成功
            $output = ['code' => 10000, 'msg' => $msg, 'status' => $update['status'], 'merchant_order_id' => $data['merchant_order_id'], 'order_id' => $order_id, 'sign' => $data['sign']];
            return Response::create($output, 'json')->options(['json_encode_param' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES]);
        } catch (\Exception $e) {
            payment_error_log(600030, input(), $e->getMessage(), false);
            return ['code' => 555, 'msg' => '系统异常', 'status' => 1];
        }
    }

    /**
     * 代付余额查询
     */
    public function paidQueryCash()
    {
        try {
            // 表单数据
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Paid.cash');
            if (true !== $result) {
                return ['code' => 15000, 'msg' => $result];
            }

            // 此商户号全部配置
            $merchant = $this->redis->get($data['merchant_id']);
            if (!$merchant || $merchant['status'] != 1) {
                return ['code' => 15001, 'msg' => '商户号不存在或者被禁用'];
            }

            $key = $merchant['value']['paid_key'];
            // 签名验证
            $sign = md5('merchant_id=' . $data['merchant_id'] . '&start_time=' . $data['start_time'] . '&random_string=' . $data['random_string'] . '&key=' . $key);
            if ($sign != $data['sign']) {
                return ['code' => 15002, 'msg' => '签名错误'];
            }

            /*
              // 查询，不能在3秒内发送相同的签名，用redis处理。
              $paid_query_cash_key = 'paid_query_cash_' . $data['merchant_id'] . $data['sign'];
              $paid_query_cash = $this->redis->has($paid_query_cash_key);
              if ($paid_query_cash) {
              \think\Log::record('代付查询余额接口不能在3秒内发送相同的签名：' . json_encode($data), 'notice');
              return ['code' => 15003, 'msg' => '不能在3秒内发送相同的签名'];
              } else {
              // 设置3秒有效期
              $this->redis->set($paid_query_cash_key, 1, 3);
              }
             */

            // 查询余额
            $info = PaymentCash::where(['merchant_id' => $data['merchant_id']])->field('paid_cash')->find();
            if ($info) {
                $paid_cash = $info['paid_cash'] / 100;
                $output = ['code' => 10000, 'msg' => '查找成功', 'paid_cash' => $paid_cash];
                return Response::create($output, 'json')->options(['json_encode_param' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES]);
            } else {
                return ['code' => 15004, 'msg' => '钱包有误'];
            }
        } catch (\Exception $e) {
            payment_error_log(600032, input(), $e->getMessage(), false);
            return ['code' => 555, 'msg' => '系统异常'];
        }
    }

    /**
     * 创建退款订单
     */
    public function refund()
    {
        try {
            // 表单数据
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Refund');
            if (true !== $result) {
                return ['code' => 16000, 'msg' => $result, 'status' => 3];
            }

            // 此商户号全部配置
            $merchant = $this->redis->get($data['merchant_id']);
            if (!$merchant || $merchant['status'] != 1) {
                return ['code' => 16001, 'msg' => '商户号不存在或者被禁用', 'status' => 3];
            }

            // 商户号配置值
            $merchant_value = $merchant['value'];
            $key = $merchant_value['key'];
            // 签名验证
            $sign = md5('merchant_id=' . $data['merchant_id'] . '&merchant_order_id=' . $data['merchant_order_id'] . '&old_merchant_order_id=' . $data['old_merchant_order_id'] . '&cash=' . $data['cash'] . '&notify_url=' . $data['notify_url'] . '&start_time=' . $data['start_time'] . '&random_string=' . $data['random_string'] . '&key=' . $key);
            if ($sign != $data['sign']) {
                return ['code' => 16002, 'msg' => '签名错误', 'status' => 3];
            }

            // 支付开关
            $payment_open = $this->redis->get('payment_open');
            if (!$payment_open || $payment_open['status'] != 1) {
                return ['code' => 16003, 'msg' => '支付关闭', 'status' => 3];
            }

            // 访问请求ip地址
            $request_ip = Request::instance()->ip();
            if ($merchant_value['pay_ip']) {
                if (!in_array($request_ip, $merchant_value['pay_ip'])) {
                    return ['code' => 16004, 'msg' => '请求服务器IP不在白名单中', 'status' => 3];
                }
            }

            // 交易类型（退款）
            $trade_type = $this->redis->get('refund');
            if (!$trade_type || $trade_type['status'] != 1) {
                return ['code' => 16005, 'msg' => '交易类型已经关闭'];
            }

            // 接收的应用ID是否存在
            if ($data['app_id'] != 0) {
                if (!in_array($data['app_id'], $merchant_value['app_id'])) {
                    return ['code' => 16006, 'msg' => '应用ID不存在', 'status' => 3];
                }
            }

            // 交易类型不存在或者此商户号没有开通此交易类型
            if ($data['trade_type'] != 'refund' || !in_array($data['trade_type'], $merchant_value['trade_type'])) {
                return ['code' => 16007, 'msg' => '商户号交易类型不存在', 'status' => 3];
            }

            // 接口请求相同原商户订单号默认多少秒不能重复
            $temp_old_merchant_order_id = 'temp_refund_' . $data['old_merchant_order_id'];
            $temp_old_merchant_order_id_exist = $this->redis->has($temp_old_merchant_order_id);
            if ($temp_old_merchant_order_id_exist) {
                return ['code' => 16008, 'msg' => "相同原商户订单号60秒内重试无效", 'status' => 3];
            } else {
                $this->redis->set($temp_old_merchant_order_id, 1, 60);
            }

            // 原支付订单查询
            $pay_order_info = PaymentOrder::where('merchant_id', $data['merchant_id'])
                ->where('merchant_order_id', $data['old_merchant_order_id'])
                ->find();
            if (!$pay_order_info || $pay_order_info['status'] != 2) {
                return ['code' => 16009, 'msg' => "原商户订单号不存在或状态有误", 'status' => 3];
            }
            if ($pay_order_info['cash'] != $data['cash'] * 100) {
                return ['code' => 16010, 'msg' => "退款金额有误", 'status' => 3];
            }
            /*
            if (time() > $pay_order_info['create_time'] + 86400 * 30) {
                return ['code' => 16011, 'msg' => "退款时间超过了系统设置的订单退款时间30天", 'status' => 3];
            }
            */

            // 退款订单查询
            $refund_order_info = PaymentOrderRefund::where('merchant_id', $data['merchant_id'])
                ->where('merchant_order_id', $data['old_merchant_order_id'])
                ->where('status', '<>', 3)
                ->find();
            if ($refund_order_info) {
                return ['code' => 16012, 'msg' => "退款订单处理状态", 'status' => 3];
            }

            // 支付公司配置
            $children_company_config = $this->redis->get($pay_order_info['child_company']);
            if (!$children_company_config || $children_company_config['status'] != 1) {
                return ['code' => 16013, 'msg' => "退款公司配置关闭", 'status' => 3];
            }
            if ($children_company_config['value']['refund_open'] == 0) {
                return ['code' => 16014, 'msg' => "此订单对应公司不支持退款", 'status' => 3];
            }

            $cash = intval(strval($data['cash'] * 100));

            $pay_rate = $merchant_value['payment_type_rate'][$pay_order_info['type']];        // 支付费率
            $pay_rate_cash = round($cash * $pay_rate);                                        // 费率金额
            $deduct_cash = $cash - $pay_rate_cash;                                            // 扣除金额

            $merchant_data = PaymentCash::get(['merchant_id' => $data['merchant_id']]);
            if ($deduct_cash > $merchant_data['cash']) {
                return ['code' => 16015, 'msg' => '商户退款余额不足', 'status' => 3];
            }
            $balance = $merchant_data['cash'] - $cash;

            $order_id = date('ymdHis') . random(8);    // 平台订单号
            $now_time = time();

            // 商户发送参数
            $merchant_order_create_param = [
                'version' => $data['version'], // 版本号
                'merchant_id' => $data['merchant_id'], // 商户号
                'merchant_order_id' => $data['merchant_order_id'], // 退款商户订单号
                'old_merchant_order_id' => $data['old_merchant_order_id'], // 原商户订单号
                'app_id' => $data['app_id'], // 应用id
                'cash' => $data['cash'], // 退款金额（元）
                'trade_type' => $data['trade_type'], // 交易类型：比如充值、代付
                'body' => $data['body'], // 退款说明
                'name' => $data['name'], // 姓名
                'id_card' => $data['id_card'], // 身份证号
                'mobile' => $data['mobile'], // 手机号
                'notify_open' => $data['notify_open'], // 通知开关
                'notify_url' => $data['notify_url'], // 通知地址
                'ip' => $data['ip'], // 客户端ip
                'user_id' => $data['user_id'], // 用户id
                'channel_id' => $data['channel_id'], // 渠道id
                'format' => $data['format'], // 返回格式
                'sign_type' => $data['sign_type'], // 签名类型
                'extra' => isset($data['extra']) ? $data['extra'] : '', // 商户自定义备注
                'start_time' => $data['start_time'], // 订单开始时间（时间戳）
                'random_string' => $data['random_string'], // 随机字符串
                'sign' => $data['sign'], // 签名
                'key' => $key, // 密钥
                'request_ip' => $request_ip, // 访问请求ip地址
            ];

            $local_order_param = [
                'order_id' => $order_id, // 平台订单号
                'old_order_id' => $pay_order_info['order_id'], // 原平台订单号
                'merchant_id' => $data['merchant_id'], // 商户号
                'merchant_order_id' => $data['merchant_order_id'], // 退款商户订单号
                'old_merchant_order_id' => $data['old_merchant_order_id'], // 原商户订单号
                'app_id' => $data['app_id'], // 应用id
                'cash' => $cash, // 退款金额
                'deduct_cash' => $deduct_cash, // 扣除金额
                'old_cash' => $pay_order_info['cash'], // 原金额
                'balance' => $balance, // 余额
                'trade_type' => $data['trade_type'], // 交易类型：比如充值、代付
                'body' => $data['body'], // 退款说明     
                'user_id' => $data['user_id'], // 用户id
                'create_time' => $now_time, // 订单创建时间
                'update_time' => $now_time, // 订单更新时间
                'company' => $pay_order_info['company'], // 支付公司名称
                'child_company' => $pay_order_info['child_company'], // 支付公司子商户号名称
                'status' => 1, // 状态
                'other_order_id' => '', // 第三方订单号
                'create_param' => json_encode($merchant_order_create_param, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), // 创建商户号发送参数数据
            ];
            // 捕获异常,可能代付订单表数据写入失败
            try {
                PaymentOrderRefund::create($local_order_param);
            } catch (\Exception $e) {
                payment_log(100022, $local_order_param, $e->getMessage());
                return ['code' => 16016, 'msg' => '商户退款订单号重复', 'status' => 3];
            }

            // 捕获异常,扣除商户余额
            try {
                PaymentCash::where(['merchant_id' => $data['merchant_id']])
                    ->dec('cash', $deduct_cash)
                    ->inc('refund_sum_cash', $deduct_cash)
                    ->inc('refund_count', 1)
                    ->update(['update_time' => time()]);
            } catch (\Exception $e) {
                PaymentOrderRefund::where(['order_id' => $order_id])->update(['status' => 4, 'update_time' => time()]);
                payment_error_log(900000, $local_order_param, $e->getMessage());
                return ['code' => 16017, 'msg' => '商户余额错误', 'status' => 3];
            }

            // 发送给第三方支付公司参数（退款）
            $param['merchant_id'] = $data['merchant_id'];                        // 商户号
            $param['order_id'] = $order_id;                                      // 平台订单号
            $param['old_order_id'] = $pay_order_info['order_id'];                // 原平台订单号
            $param['merchant_order_id'] = $data['merchant_order_id'];            // 退款订单号
            $param['old_merchant_order_id'] = $data['old_merchant_order_id'];    // 原商户订单号
            $param['cash'] = $data['cash'];                                      // 退款金额 
            $param['old_cash'] = $pay_order_info['cash'] / 100;                  // 原订单金额 
            $param['body'] = $data['body'];                                      // 退款说明
            $param['name'] = $data['name'];                                      // 姓名
            $param['id_card'] = $data['id_card'];                                // 身份证
            $param['mobile'] = $data['mobile'];                                  // 手机号
            $param['ip'] = $data['ip'];                                          // 客户端ip
            $param['user_id'] = $data['user_id'];                                // 用户id
            $param['channel_id'] = $data['channel_id'];                          // 渠道id 
            $param['now_time'] = $now_time;                                      // 现在时间 

            // 实例化第三方订单模型
            $payment_order_refund_obj = new PaymentOrderRefund();

            $payment_company = $pay_order_info['company'];
            // 选择对应的公司                    
            $resarray = $payment_order_refund_obj->$payment_company($param, $children_company_config['value']);

            // 状态：1:处理中 2:成功 3:失败 4:异常 
            $code = isset($resarray['code']) ? $resarray['code'] : '';
            $update['status'] = $code == 300 ? 3 : 1;
            $update['other_order_id'] = isset($resarray['other_order_id']) ? $resarray['other_order_id'] : '';
            $update['return_param'] = isset($resarray['return_param']) ? substr($resarray['return_param'], 0, 60000) : '';
            $update['update_time'] = time();

            $msg = isset($resarray['msg']) ? $resarray['msg'] : '未知错误';
            $msg = '提示：' . $msg;
            // 捕获异常,代付订单表数据改为失败
            try {
                PaymentOrderRefund::where(['order_id' => $order_id])->update($update);
            } catch (\Exception $e) {
                payment_error_log(900002, $local_order_param, $e->getMessage());
            }

            if ($update['status'] == 3) {

                // 捕获异常,扣除商户代付余额(还原)
                try {
                    PaymentCash::where(['merchant_id' => $data['merchant_id']])
                        ->inc('cash', $deduct_cash)
                        ->dec('refund_sum_cash', $deduct_cash)
                        ->dec('refund_count', 1)
                        ->update(['update_time' => time()]);
                } catch (\Exception $e) {
                    PaymentOrderRefund::where(['order_id' => $order_id])->update(['status' => 4, 'update_time' => time()]);
                    payment_error_log(900004, $local_order_param, $e->getMessage());
                }

                return ['code' => 16018, 'msg' => $msg, 'status' => 3];
            }

            // 创建订单完成，成功
            $output = ['code' => 10000, 'msg' => $msg, 'status' => $update['status'], 'merchant_order_id' => $data['merchant_order_id'], 'old_merchant_order_id' => $data['old_merchant_order_id'], 'order_id' => $order_id, 'sign' => $data['sign']];
            return Response::create($output, 'json')->options(['json_encode_param' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES]);
        } catch (\Exception $e) {
            payment_error_log(900006, input(), $e->getMessage(), false);
            return ['code' => 555, 'msg' => '系统异常', 'status' => 1];
        }
    }

    /**
     * 根据平台订单号，调用第三方支付
     */
    public function order()
    {
        try {
            config('default_return_type', 'html');
            // 表单数据
            $data = $this->request->param();
            // 验证
            $result = $this->validate($data, 'Order.order');
            if (true !== $result) {
                return $this->fetch('order', ['msg' => $result]);
            }

            if (time() > 300 + $data['start_time']) {
                return $this->fetch('order', ['msg' => '订单时间过期']);
            }
            // 过期时间
            $expire_time = 300 - (time() - $data['start_time']);

            // 令牌
            $token = $this->redis->get('token');

            $token_value = $token['value'];
            $sign = md5($data['order_id'] . $data['start_time'] . $token_value);
            if ($sign != $data['sign']) {
                return $this->fetch('order', ['msg' => '签名错误']);
            }

            // 查找订单
            $info = PaymentOrder::where(['order_id' => $data['order_id']])->field(true)->find();
            if ($info) {
                if ($info['status'] == 2) {
                    return $this->fetch('order', ['msg' => '此订单已经支付，请勿重复支付']);
                }

                if (isset($data['preserve_url']) && $data['preserve_url'] == 1) {
                    $order_pay_url_key = 'order_pay_url_' . $data['order_id'];
                    $order_pay_url = $this->redis->get($order_pay_url_key);
                    if ($order_pay_url) {
                        header("Location: {$order_pay_url}");
                        exit;
                    }
                }

                /*
                  $agent = Request::instance()->server('HTTP_USER_AGENT');
                  $device = 'pc';
                  if (stripos($agent, 'windows nt')) {
                  $device = 'pc';
                  }
                  if (stripos($agent, 'iphone')) {
                  $device = 'iphone';
                  }
                  if (stripos($agent, 'ipad')) {
                  $device = 'ipad';
                  }
                  if (stripos($agent, 'android')) {
                  $device = 'android';
                  }
                  if (stripos($agent, 'micromessenger')) {
                  $device = 'wechat';
                  }
                  if (stripos($agent, 'alipayclient')) {
                  $device = 'alipay';
                  }
                 */

                $is_mobile = Request::instance()->isMobile() ? 1 : 0;

                // 扫码
                if (isset($data['content'])) {

                    if (isset($data['encrypt']) && $data['encrypt'] == 1) {
                        $data['content'] = base64_decode($data['content']);
                    }

                    $content = $data['content'];

                    include_once Env::get('extend_path') . 'phpqrcode' . DIRECTORY_SEPARATOR . 'phpqrcode.php';
                    $file_name = Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . 'ewm' . DIRECTORY_SEPARATOR . 'qrcode' . DIRECTORY_SEPARATOR . $data['order_id'] . '.png';  // 图片路径
                    \QRcode::png($content, $file_name, 'L', 10, 2);
                    $img = Request::instance()->domain() . '/' . 'ewm/' . 'qrcode/' . $data['order_id'] . '.png';
                    //$res = "<div style='text-align:center'><img src='{$img}' width='300' height='300' /></div>";
                    //return Response::create($res, 'html');

                    config('default_return_type', 'html');
                    $this->assign('img', $img);
                    $this->assign('order_id', $info['order_id']);
                    $this->assign('cash', $info['cash'] / 100);
                    $this->assign('content', $content);
                    $this->assign('is_mobile', $is_mobile);
                    $this->assign('expire_time', $expire_time);
                    $this->assign('jump_url', $data['jump_url']);
                    $view = 'wechat';
                    if ($info['type'] == 'alipay_scan_code' || $info['type'] == 'alipay_h5') {
                        $view = 'alipay';

                        /*
                          支付宝跳转一
                          $jump_alipay_url = 'alipays://platformapi/startapp?appId=20000067&url=' . urlencode($content);

                          支付宝跳转二
                          $jump_alipay_url = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2017062707578742&scope=auth_user&redirect_uri=' . urlencode($content);
                          $jump_alipay_url = 'alipays://platformapi/startapp?appId=20000067&url=' . urlencode($jump_alipay_url);

                          支付宝跳转三
                          $jump_alipay_url = 'alipays://platformapi/startapp?saId=10000007&qrcode=' . urlencode($content);
                          $jump_alipay_url = 'https://render.alipay.com/p/s/i/?scheme=' . urlencode($jump_alipay_url);

                          支付宝跳转四
                          $jump_alipay_url = 'alipays://platformapi/startapp?saId=10000007&clientVersion=3.7.0.0718&qrcode=' . urlencode($content);
                          $jump_alipay_url = 'https://ds.alipay.com/?from=mobilecodec&scheme=' . urlencode($jump_alipay_url);

                          支付宝跳转五
                          $jump_alipay_url = 'alipays://platformapi/startapp?appId=20000067&url=' . urlencode($content);
                          $jump_alipay_url = 'https://render.alipay.com/p/s/i/?scheme=' . urlencode($jump_alipay_url);
                          $jump_alipay_url = 'alipays://platformapi/startapp?appId=20000067&url=' . urlencode($jump_alipay_url);
                          $jump_alipay_url = 'https://render.alipay.com/p/s/i/?scheme=' . urlencode($jump_alipay_url);
                         */

                        $jump_alipay_url = 'alipays://platformapi/startapp?appId=20000067&url=' . urlencode($content);

                        $this->assign('jump_alipay_url', $jump_alipay_url);
                    }
                    if ($info['type'] == 'unionpay_scan_code') {
                        $view = 'unionpay';
                    }
                    return $this->fetch($view);

                    /*
                      header('Content-Type: image/png');
                      include_once Env::get('extend_path') . 'phpqrcode' . DIRECTORY_SEPARATOR . 'phpqrcode.php';
                      $value = $data['content'];               // 二维码内容
                      $errorCorrectionLevel = 'L';             // 容错级别
                      $matrixPointSize = 10;                   // 生成图片大小
                      // 生成二维码图片
                      $object = new \QRcode();
                      $object->png($value, false, $errorCorrectionLevel, $matrixPointSize, 2);
                      exit;
                     */
                }

                // 实例化第三方订单模型
                $other_order_obj = new PaymentOtherOrder();
                $company = $info['company'] . 'Go';

                $company_config = $this->redis->get($info['company']);
                $child_company_config = $this->redis->get($info['child_company']);
                // 合并支付公司默认商户号和子商户号配置
                $company_merge_values = array_merge($company_config['value'], $child_company_config['value']);
                $resdata = $other_order_obj->$company($info, $company_merge_values);
                $res = json_encode($resdata);
                Log::record("封装第三方创建订单失败：{$company}：内容：{$res}", 'notice');
                // 一般不执行下面代码
                return $this->fetch('order', ['msg' => '支付错误']);
            } else {
                return $this->fetch('order', ['msg' => '订单不存在']);
            }
        } catch (\Exception $e) {
            payment_error_log(600034, input(), $e->getMessage(), false);
            return ['code' => 555, 'msg' => '系统异常'];
        }
    }

    /**
     * 支付跳转地址
     */
    public function returl()
    {
        try {
            config('default_return_type', 'html');
            // 表单数据
            $data = $this->request->param();
            // 验证
            $result = $this->validate($data, 'Order.returl');
            if (true !== $result) {
                return $this->fetch('order', ['msg' => $result]);
            }

            // 查找订单
            $info = PaymentOrder::where(['order_id' => $data['order_id']])->field(true)->find();
            if ($info) {
                if ($info['create_time'] + 600 < time()) {
                    return $this->fetch('order', ['msg' => '超过有效期']);
                }
                return $this->fetch('returl');

                $create_param = json_decode($info['create_param'], true);
                $return_url = $create_param['return_url'];
                $key = $create_param['key'];
                $arr['merchant_order_id'] = $info['merchant_order_id'];
                $arr['type'] = $info['type'];
                $arr['cash'] = $info['cash'] / 100;
                $arr['status'] = $info['status'];
                $arr['time'] = time();
                $arr['sign'] = md5('merchant_order_id=' . $arr['merchant_order_id'] . '&type=' . $arr['type'] . '&cash=' . $arr['cash'] . '&status=' . $arr['status'] . '&time=' . $arr['time'] . '&key=' . $key);

                $urlval = http_build_query($arr);
                $url = strpos($return_url, '?') !== false ? $return_url . '&' . $urlval : $return_url . '?' . $urlval;

                header("Location: {$url}");
                exit;
            } else {
                return $this->fetch('order', ['msg' => '订单不存在']);
            }
        } catch (\Exception $e) {
            payment_error_log(600036, input(), $e->getMessage(), false);
            return ['code' => 555, 'msg' => '系统异常'];
        }
    }

    /**
     * 封装跳转网址
     */
    public function url()
    {
        try {
            $wz = $this->request->param('wz');
            $url = base64_decode($wz);
            if (stripos($url, 'http') !== false) {
                echo "<!DOCTYPE html><html><head><meta http-equiv='refresh' content='0;url={$url}'></head><body></body></html>";
                exit;
            }
        } catch (\Exception $e) {
            payment_error_log(600038, input(), $e->getMessage(), false);
            return ['code' => 555, 'msg' => '系统异常'];
        }
    }
}
